首页 > 其他 > 详细

leetcode--Letter Combinations of a Phone Number

时间:2014-02-01 13:54:10      阅读:365      评论:0      收藏:0      [点我收藏+]

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.

 

Brute force method can be accepted by leetcode online judge.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        String[] keyboard = new String[]{"","","abc","def","ghi","jkl","mno",
                                                 "pqrs","tuv","wxyz"};
        ArrayList<String> result = new ArrayList<String>();
        result.add("");
        for(int i = 0; i < digits.length(); ++i){
            int k = digits.charAt(i) - 48;
            if(k != 0 && k != 1){
                ArrayList<String> temp = new ArrayList<String>();
                while(!result.isEmpty()){
                    String s = result.remove(0);
                    for(int j = 0; j < keyboard[k].length(); ++j){
                        StringBuffer stb = new StringBuffer(s);
                        stb.append(keyboard[k].charAt(j));
                        temp.add(stb.toString());
                    }
                }
                result = temp;
            }
        }
        return result;
    }
}

  

leetcode--Letter Combinations of a Phone Number

原文:http://www.cnblogs.com/averillzheng/p/3536934.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!