算法练习--LeetCode--17. Letter Combinations of a Phone Numbe
大意是指要把输入的数字按照手机键盘的映射关系转成可能的字符串
Note:虽然题目中给出输入数字在 0 => " " 1 => "*" ? 基本分析:
"0" : [" "],"1" : ["*"],"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(s: String) -> [String] { if s 为空字符串, return 空数组 if cache 不包含 s { cache[s] = cache[s的第一个字符] * letterCombinations(s除了第一字符以外剩下的部分的结果) } return cache[s] } ? 代码// Swift Code class Solution { var cache: [String : [String]] = [ "0" : [" "],"z"] ] func letterCombinations(_ digits: String) -> [String] { if digits.isEmpty { return [] } if !cache.keys.contains(digits) { cache[digits] = letterCombinations(String(digits.prefix(1))).flatMap({ (s) -> [String] in letterCombinations(String(digits.suffix(digits.count - 1))).map { s + $0 } }) } return cache[digits]! } } ? TestCase
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |