zoukankan      html  css  js  c++  java
  • LeetCode #17 Letter Combinations of a Phone Number

    LeetCode #17 Letter Combinations of a Phone Number

    Question

    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.

    img

    Input:Digit string "23"
    Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
    

    Solution

    Approach #1

    class Solution {
        func letterCombinations(_ digits: String) -> [String] {
            return stringsFromDigits(Array(digits.utf16), index: 0)
        }
        
        func stringsFromDigits(_ digits: [UInt16], index: Int) -> [String] {
            if digits.isEmpty { return [] }
            let current = stringsFromUInt16(digits[index])
            if index == digits.count - 1 { return current }
            let more = stringsFromDigits(digits, index: index + 1)
            var results: [String] = []
            for c in current {
                for m in more {
                    results.append(c + m)
                }
            }
            return results
        }
        
        func stringsFromUInt16(_ n: UInt16) -> [String] {
            let zero = "0".utf16.first!
            switch n {
            case zero, zero + 1:
                return [String(utf16CodeUnits: [n], count: 1)]
            case let n where n > zero + 1 && n < zero + 7:
                let a = "a".utf16.first!
                var strs: [String] = []
                for i in UInt16(0)..<UInt16(3) {
                    let s = String(utf16CodeUnits: [(n - zero - UInt16(2)) * UInt16(3) + i + a], count: 1)
                    strs.append(s)
                }
                return strs
            case zero + 7:
                return ["p", "q", "r", "s"]
            case zero + 8:
                return ["t", "u", "v"]
            case zero + 9:
                return ["w", "x", "y", "z"]
            default:
                return []
            }
        }
    }
    

    转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6900936.html

  • 相关阅读:
    前端构建工具gulpjs的使用介绍及技巧
    mysql /*! 50100 ... */ 条件编译
    linux 硬连接与软连接
    Linux 数据流重定向
    倒排索引
    sed 常用的功能
    linux mysql安装
    mysql help
    linux 命令行选项
    mysql 主主复制的配置流程
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/6900936.html
Copyright © 2011-2022 走看看