Skip to content

Commit

Permalink
Swift: 17. Letter Combinations of a Phone Number
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleksandr committed Aug 15, 2023
1 parent 7c19317 commit 3f71e0a
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions swift/0017-letter-combinations-of-a-phone-number.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
private let numberLetters: [Character: String] = [
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
]
func letterCombinations(_ digits: String) -> [String] {
guard !digits.isEmpty else { return [] }
var result: [String] = []
var digits = digits.map { $0 }
func generateCombinations(_ index: Int, _ path: String) {
guard index < digits.count else {
result.append(path)
return
}
let digit = digits[index]
if let letters = numberLetters[digit] {
for letter in letters {
generateCombinations(index + 1, path + "\(letter)")
}
}
}
generateCombinations(0, "")
return result
}
}

0 comments on commit 3f71e0a

Please sign in to comment.