Skip to content

Commit 3f71e0a

Browse files
author
Aleksandr
committed
Swift: 17. Letter Combinations of a Phone Number
1 parent 7c19317 commit 3f71e0a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
private let numberLetters: [Character: String] = [
3+
"2": "abc",
4+
"3": "def",
5+
"4": "ghi",
6+
"5": "jkl",
7+
"6": "mno",
8+
"7": "pqrs",
9+
"8": "tuv",
10+
"9": "wxyz"
11+
]
12+
func letterCombinations(_ digits: String) -> [String] {
13+
guard !digits.isEmpty else { return [] }
14+
var result: [String] = []
15+
var digits = digits.map { $0 }
16+
func generateCombinations(_ index: Int, _ path: String) {
17+
guard index < digits.count else {
18+
result.append(path)
19+
return
20+
}
21+
let digit = digits[index]
22+
if let letters = numberLetters[digit] {
23+
for letter in letters {
24+
generateCombinations(index + 1, path + "\(letter)")
25+
}
26+
}
27+
}
28+
generateCombinations(0, "")
29+
return result
30+
}
31+
}

0 commit comments

Comments
 (0)