问题:

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.
Example:
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

官方难度:

Medium

翻译:

给定一个数字组成的字符串,返回所有可能的字母集合。数字和字母的映射关系就像电话上显示的一样。

例子:

输入字符串:"23"

输出集合:["ad","ae","af","bd","be","bf","cd","ce","cf"]

集合内的元素顺序没有规定。

方法一:

  1. 首先需要定义一个数值-字符的字典转译方法,使用长度为8的字符串数组,存放a-z的字母,然后根据输入的int值,返回一个char[]类型数组。
  2. 输入数字字符长度为0时,返回的是一个空的集合,而不是长度为1,包含一个空字符串的集合,需要特殊处理。
  3. 先将空字符串放入集合,然后开启递归。
  4. 递归终点是数字字符串长度为0,返回集合。
  5. 每次遍历集合的所有元素,根据数字字符串的第一个数字,排除所有可能性,将结果放回入参的集合,作为下一次递归的入参。
  6. 截取数字字符串的第一个数字的方法是:targetDigit.charAt(0)-‘a’。
  7. 注意入参检查

方法一的解题代码:

 public static List<String> letterCombinations(String digits) {
if (digits == null) {
throw new IllegalArgumentException("Input error");
}
String copyDigits = digits;
while (copyDigits.length() > 0) {
int i = copyDigits.charAt(0) - '0';
if (i < 2 || i > 9) {
throw new IllegalArgumentException("Input error");
}
copyDigits = copyDigits.substring(1);
}
// 只接受2-9的数值字符串
List<String> source = new LinkedList<>();
if (digits.equals("")) {
return source;
}
// 初始size需要等于1,不然之后不能循环
source.add("");
return format(source, digits);
} // 递归方法
private static List<String> format(List<String> source, String targetDigit) {
if (targetDigit.length() == 0) {
return source;
}
List<String> result = new LinkedList<>();
// 第一个数
int first = targetDigit.charAt(0) - '0';
char[] cArray = dict(first);
// source集合和targetDigit第一个数字对应字典的全排列
for (String str : source) {
for (char c : cArray) {
result.add(str + c);
}
}
// 将target转成source,继续递归
return format(result, targetDigit.substring(1));
} private static char[] dict(int num) {
String[] mappping = new String[] { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
return mappping[num - 2].toCharArray();
}

letterCombinations

方法二:

1.  转译字典还能使用其他方法实现,不使用字符串数组,获得返回的char型数组的第一个值,然后依次添加。

2.  有一个隐藏的性质,得到的每一个字母字符串长度,与最初的数字字符串长度是一样的。然后指定声明集合为LinkedList,利用LinkedList.remove()方法删除并返回第一个元素,以及LinkedList.peek()方法得到集合的第一个元素。

3.  利用三次循环,外循环获取对应数字,除了方法一中的办法,还可以使用Character包装类自带的方法:Character.getNumbericValue()。

4.  中循环,使用while()循环判断集合的第一个元素的长度是否等于i,然后删除第一个元素,再用内循环转译数字凭借字符串,放入集合的尾部,这样可以保证遍历上一次集合的值。

方法二的解题代码:

     public static List<String> letterCombinations2(String digits) {
LinkedList<String> list = new LinkedList<String>();
if (digits.length() == 0) {
return list;
}
list.add("");
for (int i = 0; i < digits.length(); i++) {
int x = Character.getNumericValue(digits.charAt(i));
while (list.peek().length() == i) {
// 删除集合第一个元素并返回
String s = list.remove();
for (char c : dict2(x)) {
list.add(s + c);
}
}
}
return list;
} // 数字-字母转译字典
private static char[] dict2(int num) {
char[] result;
if (num == 9 || num == 7) {
result = new char[4];
} else {
result = new char[3];
}
// 注意7和9代表4个字母
char start;
if (num < 8) {
start = (char) ('a' + (num - 2) * 3);
} else {
start = (char) ('a' + (num - 2) * 3 + 1);
}
result[0] = start;
result[1] = (char) (start + 1);
result[2] = (char) (start + 2);
if (num == 9 || num == 7) {
result[3] = (char) (start + 3);
}
return result;
}

letterCombinations2

备注

  1. 就效率而言,两个方法是相同的,并没有高下之分。方法一的用法更加便于理解,但是其中使用了递归,所以在空间利用上要明显劣于方法二。推荐使用方法二。

相关链接:

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q017.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.017:Letter Combinations of a Phone Number的更多相关文章

  1. LeetCode OJ:Letter Combinations of a Phone Number(数字字母组合)

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  2. LeetCode第[17]题(Java):Letter Combinations of a Phone Number

    题目:最长公共前缀 难度:EASY 题目内容: Given a string containing digits from 2-9 inclusive, return all possible let ...

  3. lintcode 中等题:Letter Combinations of a Phone Number 电话号码的字母组合

    题目 电话号码的字母组合 给一个数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合. 下图的手机按键图,就表示了每个数字可以代表的字母. 样例 给定 "23" 返回 [& ...

  4. Letter Combinations of a Phone Number:深度优先和广度优先两种解法

    Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations ...

  5. 《LeetBook》leetcode题解(17):Letter Combinations of a Phone Number[M]

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  6. [LintCode] Letter Combinations of a Phone Number 电话号码的字母组合

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  7. 69. Letter Combinations of a Phone Number

    Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations ...

  8. 【leetcode】Letter Combinations of a Phone Number

    Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations ...

  9. Letter Combinations of a Phone Number - LeetCode

    目录 题目链接 注意点 解法 小结 题目链接 Letter Combinations of a Phone Number - LeetCode 注意点 可以不用按字典序排序 解法 解法一:输入的数字逐 ...

随机推荐

  1. 控制台屏蔽某console的输出

    有时候需要调试一个在线网站. 打开 chrome 控制台,其中有一些 console.log 不停的输出. 这样的话就影响了我们使用控制台调试页面. 那么怎样不让那一句(或多句)console.log ...

  2. paip.2013年技术趋势以及热点 v2.0 cae

    paip.2013年技术趋势以及热点 v2.0 cae HTML5 多核编程 物联网 可穿戴计算设备 3. 物联网 无论是M2M(机器对机器)通信应用,还是NFC(进距离通信)技术,都是物联网的组成部 ...

  3. fir.im Weekly - 如何用 iPad 创造技术生产力

    传播学大师麦克卢汉有一个著名理论--「 媒介即讯息,媒介是人的延伸」,在当代,表现更为明显的是「工具即为人的延伸」,工具使人自由.那么,我们究竟需要什么样的工具释放技术生产力?本期 fir.im We ...

  4. Codeforces Round #380 (Div. 2) 总结分享

    B. Spotlights 题意 有n×m个格子的矩形舞台,每个格子里面可以安排一个演员或聚光灯,聚光灯仅可照射一个方向(俯视,上下左右).若聚光灯能照到演员,则称为"good positi ...

  5. 领会CSS,实际中的研究

    虽懂却不会,真是可怕,自认懂却了无. 善用CSS属性选择器 在用于区别和唯一的情况下完全可以使用属性选择器,而没有必要使用class或id p[city="http://www.css.co ...

  6. 元素多层嵌套,JS获取问题

    如果一段html嵌套过多,在js中获取还是比较麻烦的,我写了几套方案,大家可以参考参考,如果你有好的方法,也分享出来,让我们瞧瞧. HTML: <!DOCTYPE html> <ht ...

  7. Mysql存储过程语法

    一口气弄完了! 一.条件语句if-then-else: create procedure demo_1(in param int) begin declare var int; ; then inse ...

  8. Network - FTP与SFTP

    FTP --- FTP File Transfer SFTP --- SSH File Transfer 缩写 名称 协议与端口 安全策略 特征描述 守护进程(linux) 应用场景 SFTP SSH ...

  9. 在java中使用redis

    在java中使用redis很简单,只需要添加jedist.jar,通过它的api就可以了.而且,api和redis的语法几乎完全相同.以下简单的测试: 参考:http://www.runoob.com ...

  10. DNS解析全过程及原理

    DNS解析原理及过程. 当用户访问我们网站一个网页时,他需要经过以下步骤: 1)找到这个网页的存放服务器: 2)服务器将用户的请求信息接入: 3)服务器通过文件路径(URL)查找用户请求网页: 4)用 ...