17. Letter Combinations of a Phone Number
来源:互联网 发布:脸型测试软件 编辑:程序博客网 时间:2024/06/01 09:36
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.
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.
public class Solution { String[] strs = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { List<String> res = new ArrayList<String>(); if (digits == null || digits.length() == 0) { return res; } for(char ch: digits.toCharArray()) { int digit = ch - '0'; if (digit < 2 || digit > 9) { return res; } } helper(digits, res, new StringBuilder(), 0); return res; } private void helper(String digits, List<String> list, StringBuilder sb, int index) { if (index == digits.length()) { list.add(sb.toString()); return; } String chs = strs[digits.charAt(index) - '0']; for (int i = 0; i < chs.length(); i ++) { sb.append(chs.charAt(i)); helper(digits, list, sb, index + 1); sb.deleteCharAt(sb.length() - 1); } }}也可以采用FIFO的思路先进先出,每出来一个,加上下个数字的每一个字母,再存进去。代码如下:
public List<String> letterCombinations(String digits) { LinkedList<String> ans = new LinkedList<String>(); String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; ans.add(""); for(int i =0; i<digits.length();i++){ int x = Character.getNumericValue(digits.charAt(i)); while(ans.peek().length()==i){ String t = ans.remove(); for(char s : mapping[x].toCharArray()) ans.add(t+s); } } return ans;}
0 0
- 17.Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- Channel is unrecoverably broken and will be disposed!
- 云核心网解决方案及其演进方向
- 忏悔
- 数字电路1 -三极管开关
- log4j+commons-logging结合使用
- 17. Letter Combinations of a Phone Number
- dedecms上传图片附件文件夹按年月保存
- mybatis 需要注意的点 MyBatis 插入空值时,需要指定JdbcType
- classpath和classpath*和配置文件路径
- 动态添加删除网卡
- 为 instance 配置静态 IP
- 最简单的 RabbitMQ 监控方法
- instance “error” 了怎么办?- 每天5分钟玩转 OpenStack(159)
- Troubleshooting OpenStack 瘫痪