17. Letter Combinations of a Phone Number

/*
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"))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容