Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save spurscho/682a3e623851ed65124b4571f757d5c6 to your computer and use it in GitHub Desktop.
Save spurscho/682a3e623851ed65124b4571f757d5c6 to your computer and use it in GitHub Desktop.
17. Letter Combinations of a Phone Number
class Solution {
let phoneDict: [Int : String] = [
2 : "abc",
3 : "def",
4 : "ghi",
5 : "jkl",
6 : "mno",
7 : "pqrs",
8 : "tuv",
9 : "wxyz"
]
func letterCombinations(_ digits: String) -> [String] {
var combinations = [String]()
guard digits.isEmpty != true else {
return combinations
}
for digit in digits {
guard let number = Int(String(digit)), let letters = phoneDict[number] else {
continue
}
var newCombinations = [String]()
for letter in letters {
if combinations.count == 0 {
newCombinations.append(String(letter))
} else {
newCombinations = newCombinations + combinations.map({$0 + String(letter)})
}
}
combinations = newCombinations
}
return combinations
}
}
let sol = Solution()
let val = "23"
print("\n\(sol.letterCombinations(val))")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment