码迷,mamicode.com
首页 > 编程语言 > 详细

Letter Combinations of a Phone Number leetcode java

时间:2014-07-31 05:22:05      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   os   strong   io   

题目

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.

bubuko.com,布布扣

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

 

Letter Combinations of a Phone Number leetcode java,布布扣,bubuko.com

Letter Combinations of a Phone Number leetcode java

标签:style   blog   http   color   java   os   strong   io   

原文地址:http://www.cnblogs.com/springfor/p/3879829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!