Created
January 6, 2020 05:41
-
-
Save spurscho/682a3e623851ed65124b4571f757d5c6 to your computer and use it in GitHub Desktop.
17. Letter Combinations of a Phone Number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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