Letter Combinations of a Phone Number
来源:互联网 发布:淘宝店铺等级 编辑:程序博客网 时间:2024/05/17 04:08
原题:
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"].
即给定一串数字,返回所有这串数字敲在九键上所有可能出现的情况。
思考过程:
一开始是想完成字母表:
String alphabet[] = {"","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};之后简单遍历所有情况。结果发现遍历不成。后来发现这道题并不见得,至少用到迭代或者递归才可以解开。有的人用的深度优先遍历。
解题思路:迭代
从第一个输入的数字开始,找到输入这一个数字所有可能的结果,将其存储在一个List<String>里。再找到所有输入下一个数字的可能的结果,还是存到List里,以此类推。
结果代码:
public List<String> letterCombinations(String digits) { String alphabet[] = {"","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; List<String> res = new ArrayList<>(); if (digits.length() == 0) return res; for (int i = 0;i < alphabet[digits.charAt(0) - '0'].length();i++) res.add(String.valueOf(alphabet[digits.charAt(0) - '0'].charAt(i))); for (int i = 1; i < digits.length(); i++) { List<String> v = new ArrayList<>(); for (int j = 0;j < res.size();j++) for (int k = 0;k < alphabet[digits.charAt(i) - '0'].length();k++) v.add(res.get(j) + alphabet[digits.charAt(i) - '0'].charAt(k)); res = v; }return res;}
阅读全文
0 0
- LeetCode: Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode18:Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- [LintCode 98] 链表排序(Python)
- UOJ NOIP2015 斗地主 [搜索]
- Spring事务管理
- Android用Okhttp搭建自己的网络框架
- LeetCode 81. Search in Rotated Sorted Array II
- Letter Combinations of a Phone Number
- mongodb 索引的创建于删除
- 使用sqlcmd对sql进行操作
- thinkphp增删改查的where条件句的一些例子
- 递归版冒泡排序
- 关于easyui-datebox日期最大默认值和起止日期验证的问题
- 实现mysql定时任务的方法(二)
- Draw Something
- Angular4记账webApp练手项目之二(在angular4项目中使用Angular WeUI)