美文网首页
17.电话号码的字母组合

17.电话号码的字母组合

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-08 10:13 被阅读0次

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
    }
}

相关文章

网友评论

      本文标题:17.电话号码的字母组合

      本文链接:https://www.haomeiwen.com/subject/hotddhtx.html