Medium
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = “23”
Output: [“ad”,”ae”,”af”,”bd”,”be”,”bf”,”cd”,”ce”,”cf”]
Example 2:
Input: digits = “”
Output: []
Example 3:
Input: digits = “2”
Output: [“a”,”b”,”c”]
Constraints:
0 <= digits.length <= 4
digits[i]
is a digit in the range ['2', '9']
.To solve the Letter Combinations of a Phone Number problem in Swift using a Solution
class, we’ll follow these steps:
Solution
class with a method named letterCombinations
that takes a string digits
as input and returns a list of all possible letter combinations.result
to store the combinations.digits
is empty, return an empty list result
.generateCombinations
to generate combinations for each digit.digits
, add the combination to the result
list.result
list containing all possible combinations.Here’s the implementation:
class Solution {
func letterCombinations(_ digits: String) -> [String] {
if digits.isEmpty {
return []
}
let letters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
var ans: [String] = []
var curr = String()
findCombinations(0, digits, letters, &curr, &ans)
return ans
}
private func findCombinations(_ start: Int, _ digits: String, _ letters: [String], _ curr: inout String, _ ans: inout [String]) {
if curr.count == digits.count {
ans.append(curr)
return
}
let index = digits.index(digits.startIndex, offsetBy: start)
let digit = digits[index]
let digitIndex = digit.wholeNumberValue!
for letter in letters[digitIndex] {
curr.append(letter)
findCombinations(start + 1, digits, letters, &curr, &ans)
curr.removeLast()
}
}
}
This implementation provides a solution to the Letter Combinations of a Phone Number problem in Swift.