LeetCode #17 Letter Combinations of a Phone Number
Question
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Solution
Approach #1
class Solution {
func letterCombinations(_ digits: String) -> [String] {
return stringsFromDigits(Array(digits.utf16), index: 0)
}
func stringsFromDigits(_ digits: [UInt16], index: Int) -> [String] {
if digits.isEmpty { return [] }
let current = stringsFromUInt16(digits[index])
if index == digits.count - 1 { return current }
let more = stringsFromDigits(digits, index: index + 1)
var results: [String] = []
for c in current {
for m in more {
results.append(c + m)
}
}
return results
}
func stringsFromUInt16(_ n: UInt16) -> [String] {
let zero = "0".utf16.first!
switch n {
case zero, zero + 1:
return [String(utf16CodeUnits: [n], count: 1)]
case let n where n > zero + 1 && n < zero + 7:
let a = "a".utf16.first!
var strs: [String] = []
for i in UInt16(0)..<UInt16(3) {
let s = String(utf16CodeUnits: [(n - zero - UInt16(2)) * UInt16(3) + i + a], count: 1)
strs.append(s)
}
return strs
case zero + 7:
return ["p", "q", "r", "s"]
case zero + 8:
return ["t", "u", "v"]
case zero + 9:
return ["w", "x", "y", "z"]
default:
return []
}
}
}
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6900936.html