LeetCode – 17. Letter Combinations of a Phone Number

題目連結:https://leetcode.com/problems/letter-combinations-of-a-phone-number/

法ㄧ: (自己寫的解法)

func letterCombinations(_ digits: String) -> [String] {
    let dic: [Character: String] = ["2" : "abc",
                                    "3" : "def",
                                    "4" : "ghi",
                                    "5" : "jkl",
                                    "6" : "mno",
                                    "7" : "pqrs",
                                    "8" : "tuv",
                                    "9" : "wxyz"]
    let digitsArr = Array(digits)
    var arr: [String] = []
    for i in 0 ..< digitsArr.count {
        arr.append(dic[digitsArr[i]]!)
    }
    var result: [String] = []
    for i in 0 ..< arr.count {
        let tmp = Array(arr[i])
        var tmpResult: [String] = []
        for j in 0 ..< tmp.count {
            if result.count == 0 {
                let val = String(tmp[j])
                tmpResult.append(val)
            } else {
                for k in 0 ..< result.count {
                    let val = String(result[k]) + String(tmp[j])
                    tmpResult.append(val)
                }
            }
        }
        result = tmpResult
    }
    return result
}

法二: (別人寫的解法[Ref])

  private let matrix: [Character:[Character]] = ["2":["a","b","c"],
                                                   "3":["d","e","f"],
                                                   "4":["g","h","i"],
                                                   "5":["j","k","l"],
                                                   "6":["m","n","o"],
                                                   "7":["p","q","r","s"],
                                                   "8":["t","u","v"],
                                                   "9":["w","x","y","z"]]
    func letterCombinations(_ digits: String) -> [String] {
        var result: [String] = []
        for ch in digits.map({ Character($0.lowercased()) }) {
            guard let chars = matrix[ch] else { break }
            guard !(result.isEmpty) else {
                chars.forEach { result.append("\($0)") }
                continue
            }
            
            let current = result
            result.removeAll()
            
            for ch in chars {
                result.append(contentsOf: current.map { $0 + "\(ch)" })
            }
        }
        return result
    }

Ref: https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/1382543/Solution-Swift%3A-Accepted-(%2B-test-cases)