From 3f71e0a70d254cfbdd3734f278dbb9885a9dd5ac Mon Sep 17 00:00:00 2001 From: Aleksandr Date: Tue, 15 Aug 2023 14:27:28 +0400 Subject: [PATCH] Swift: 17. Letter Combinations of a Phone Number --- ...etter-combinations-of-a-phone-number.swift | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 swift/0017-letter-combinations-of-a-phone-number.swift diff --git a/swift/0017-letter-combinations-of-a-phone-number.swift b/swift/0017-letter-combinations-of-a-phone-number.swift new file mode 100644 index 000000000..606c59668 --- /dev/null +++ b/swift/0017-letter-combinations-of-a-phone-number.swift @@ -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 + } +} \ No newline at end of file