美文网首页LeetCode
17. Letter Combinations of a Ph

17. Letter Combinations of a Ph

作者: 小万叔叔 | 来源:发表于2017-02-14 10:30 被阅读23次
    /*
    17. Letter Combinations of a Phone Number
    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"].
    
    
    */
    
    import Foundation
    
    func letterCombinations(_ digits: String) -> [String] {
        let length = digits.lengthOfBytes(using: .ascii)
        guard length > 0 else {
            return [String]()
        }
        //0~9
        let matchArray: [String] = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        //Error:需要先有一个初始值 ""
        var res: [String] = [""]
        let intArray: [Int] = digits.characters.map {
            Int(String($0))!
        }
    
        for i in intArray {
            var tempRes: [String] = [String]()
            for value in matchArray[i].characters {
                for valueR in res {
                    let ret = "\(valueR)\(value)"
                    tempRes.append(ret)
                }
            }
            res = tempRes
        }
    
        return res
    }
    
    print(letterCombinations("23"))
    

    相关文章

      网友评论

        本文标题: 17. Letter Combinations of a Ph

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