首页 技术 正文
技术 2022年11月14日
0 收藏 582 点赞 4,908 浏览 1417 个字
  1. Letter Combinations of a Phone Number
    Medium

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

1o-o_ 2abc 3def
4ghi_ 5jkl 6mno
7pqrs 8tuv 9wxyz
*+___ 0___ #↑__

除了0的第一个“”以外的位置的“”是为了对齐

 算法练习–LeetCode–17. Letter Combinations of a Phone Number我觉得上面那玩意儿不如图

Example:

Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

大意是指要把输入的数字按照手机键盘的映射关系转成可能的字符串

  • 不要有重复的
  • 不用在意字符串顺序(输出结果数组的排序)

Note:

虽然题目中给出输入数字在[2, 9],实测(2019-01-05) 01也有对应的映射关系

0 => " "
1 => "*"

基本分析:

  • 要求长度为n的结果,首先要求长度为n-1的结果!
  • n == 1 时候结果是已知的
        "" : [" "],
"" : ["*"],
"" : ["a", "b", "c"],
"" : ["d", "e", "f"],
"" : ["g", "h", "i"],
"" : ["j", "k", "l"],
"" : ["m", "n", "o"],
"" : ["p", "q", "r", "s"],
"" : ["t", "u", "v"],
"" : ["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]] = [
"" : [" "],
"" : ["*"],
"" : ["a", "b", "c"],
"" : ["d", "e", "f"],
"" : ["g", "h", "i"],
"" : ["j", "k", "l"],
"" : ["m", "n", "o"],
"" : ["p", "q", "r", "s"],
"" : ["t", "u", "v"],
"" : ["w", "x", "y", "z"]
] func letterCombinations(_ digits: String) -> [String] {
if digits.isEmpty { return [] }
if !cache.keys.contains(digits) {
cache[digits] = letterCombinations(String(digits.prefix())).flatMap({ (s) -> [String] in
letterCombinations(String(digits.suffix(digits.count - ))).map { s + $ }
})
}
return cache[digits]!
}
}

TestCase

  • “”
  • “23”
  • “203”
  • “213”
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,497
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298