Letter Combinations of a Phone Number

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.

思路:简单的dfs题目,遍历所有情况即可。

注意事项:StringBuffer,而不是BufferString。 另外要注意String a[]={“”,“”} 可以静态初始化; StringBuffer的deleteCharAt可以删除指定位置字符;String访问字符,charAt

另外注意询问:当输入为1时,输出? 0时输出? 以及“”时输出? 这个要考虑。。本题目的解答分别对应“”,“”,“”

  1. String digits_map[] ={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
  2. List<String> result = new ArrayList<String>();
  3. StringBuffer cur = new StringBuffer();
  4. public void helper(String digits,int start,int n) {
  5. if(start == n) {
  6. result.add(new String(cur));
  7. return;
  8. }
  9. char cchar = digits.charAt(start);
  10. String str = digits_map[cchar-'0'];
  11. for(int i=0;i< str.length();i++) {
  12. cur.append(str.charAt(i));
  13. helper(digits,start+1,n);
  14. cur.deleteCharAt(cur.length()-1);
  15. }
  16. }
  17. public List<String> letterCombinations(String digits) {
  18. if(digits==null) return result;
  19. int dlen = digits.length();
  20. if(dlen==0) {
  21. result.add(digits);
  22. return result;
  23. }
  24. helper(digits,0,dlen);
  25. return result;
  26. }
posted @ 2014-07-19 23:11  purejade  阅读(84)  评论(0编辑  收藏  举报