Letter Combinations of a Phone Number leetcode java

愛做飯的小瑩子發表於2014-07-31

題目

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的題,跟 CombinationsWord 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     }

 

 Refrence:http://rleetcode.blogspot.com/2014/02/letter-combinations-of-phone-number-java.html

 

相關文章