https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
class Solution {
var result = [String]()
func letterCombinations(_ digits: String) -> [String] {
if digits.count > 0 {
backTrack("", digits)
}
return result
}
func backTrack(_ combinationStr: String, _ nextdigit: String) {
if nextdigit.count <= 0 {
result.append(combinationStr)
} else {
//提取第一个数字
let subDigit = nextdigit[nextdigit.index(nextdigit.startIndex, offsetBy: 0)]
//获取第一个数字对应的str
let subDigitStr = getStr(subDigit)
//遍历str提取每个字符
for (_, char) in subDigitStr.enumerated() {
//获取后面的剩余数
let remainStr = nextdigit[nextdigit.index(nextdigit.startIndex, offsetBy: 1)..<nextdigit.endIndex]
//递归
backTrack(combinationStr + String(char), String(remainStr))
}
}
}
func getStr(_ key: Character) -> String {
var result = ""
switch key {
case "2":
result = "abc"
case "3":
result = "def"
case "4":
result = "ghi"
case "5":
result = "jkl"
case "6":
result = "mno"
case "7":
result = "pqrs"
case "8":
result = "tuv"
case "9":
result = "wxyz"
default:
result = ""
}
return result
}
}
网友评论