首页 > 代码库 > Letter Combinations of a Phone Number leetcode java
Letter Combinations of a Phone Number leetcode java
题目:
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.
题解:
这道题也是来算一种combination的题,跟 Combinations 和 Word Break II 都比较类似(其实和leetcode里面很多题都相似)。
代码如下:
1 public ArrayList<String> letterCombinations(String digits) {
2 ArrayList<String> result=new ArrayList<String>();
3 if (digits==null)
4 return result;
5
6 String[] keyboard={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
7 StringBuilder current=new StringBuilder();
8
9 int index=0;
10 buildResult(digits, index, current, keyboard, result);
11 return result;
12 }
13
14 private void buildResult(String digits, int index, StringBuilder current, String[] keyboard, ArrayList<String> result){
15 if (index==digits.length()){
16 result.add(current.toString());
17 return;
18 }
19
20 int num=digits.charAt(index)-‘0‘;//get integer number
21 for (int i=0; i<keyboard[num].length(); i++){
22 current.append(keyboard[num].charAt(i));
23 buildResult(digits, index+1, current, keyboard, result);
24 current.deleteCharAt(current.length()-1);
25 }
26 }
2 ArrayList<String> result=new ArrayList<String>();
3 if (digits==null)
4 return result;
5
6 String[] keyboard={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
7 StringBuilder current=new StringBuilder();
8
9 int index=0;
10 buildResult(digits, index, current, keyboard, result);
11 return result;
12 }
13
14 private void buildResult(String digits, int index, StringBuilder current, String[] keyboard, ArrayList<String> result){
15 if (index==digits.length()){
16 result.add(current.toString());
17 return;
18 }
19
20 int num=digits.charAt(index)-‘0‘;//get integer number
21 for (int i=0; i<keyboard[num].length(); i++){
22 current.append(keyboard[num].charAt(i));
23 buildResult(digits, index+1, current, keyboard, result);
24 current.deleteCharAt(current.length()-1);
25 }
26 }
Refrence:http://rleetcode.blogspot.com/2014/02/letter-combinations-of-phone-number-java.html
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。