Leetcode Letter Combinations of a Phone Number
2016-06-28 12:13
381 查看
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.
Difficulty: Medium
public class Solution {
public List<String> letterCombinations(String digits) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
List<String> list = new ArrayList<String>();
if(digits == null)
return list;
hm.put(2, "abc");
hm.put(3, "def");
hm.put(4, "ghi");
hm.put(5, "jkl");
hm.put(6, "mno");
hm.put(7, "pqrs");
hm.put(8, "tuv");
hm.put(9, "wxyz");
hm.put(0, "");
for(int i = 0; i < digits.length(); i++){
String s = hm.get(digits.charAt(i) - '0');
int len = list.size();
for(int j = 0; j < s.length(); j++){
if(len == 0){
list.add("" + s.charAt(j));
}
else{
for(int k = 0; k < len; k++){
list.add(list.get(k) + s.charAt(j));
}
}
}
for(int k = 0; k < len; k++){
list.remove(0);
}
}
return list;
}
}
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"].
Difficulty: Medium
public class Solution {
public List<String> letterCombinations(String digits) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
List<String> list = new ArrayList<String>();
if(digits == null)
return list;
hm.put(2, "abc");
hm.put(3, "def");
hm.put(4, "ghi");
hm.put(5, "jkl");
hm.put(6, "mno");
hm.put(7, "pqrs");
hm.put(8, "tuv");
hm.put(9, "wxyz");
hm.put(0, "");
for(int i = 0; i < digits.length(); i++){
String s = hm.get(digits.charAt(i) - '0');
int len = list.size();
for(int j = 0; j < s.length(); j++){
if(len == 0){
list.add("" + s.charAt(j));
}
else{
for(int k = 0; k < len; k++){
list.add(list.get(k) + s.charAt(j));
}
}
}
for(int k = 0; k < len; k++){
list.remove(0);
}
}
return list;
}
}
相关文章推荐
- 实用小技巧:在键盘没有小键盘时怎么打开任务管理器
- mysql属性与java类型对照表
- Android网络数据开关用法简单示例
- 每日一linux命令(19)-------find
- Hibernate下DB2分页算法分析
- SMTP 发送邮件 字符串拼接
- 【学习笔记】递归和分治策略
- 软件质量的三个层次
- [leetcode]367. Valid Perfect Square
- hdu 5606 tree(并查集)
- pxe-kickstart批量部署文档
- 备份图解 ---mysql 博客
- Spring为某个属性注入值或为某个方法的返回值
- 013--Floyd算法-动态规划-《算法设计技巧与分析》M.H.A学习笔记
- iOS分类和扩展(Categories和Extensions)
- 大而广不如小而美 网易云信凭什么赢在PaaS大时代?
- Leetcode Valid Sudoku
- [改善Java代码]使用Throwable获得栈信息
- Android adt bundle 开发环境配置及第一个“Hello world”程序运行
- 赛门铁克 Symantec Backup Exec 2010