Friday, November 27, 2015

[leetcode]Letter Combinations of a Phone Number

实现题 妙的地方在于做一个lookup 的string array
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public List<String> letterCombinations(String digits) {
        String[] lookup = {"  ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> result = new ArrayList<String>();
        List<String> middle = new ArrayList<String>();
        for (int i = 0; i < digits.length(); i++){
            int number = digits.charAt(i) - '0';
            String temp = lookup[number];
            for(int j = 0; j < temp.length(); j++){
                if (result.isEmpty()){
                    middle.add(temp.charAt(j)+"");
                }else{
                    for(String prev: result){
                        middle.add(prev+temp.charAt(j));
                    }
                }
            }
            List<String>tempList = middle;
            middle = result;
            result = tempList;
            middle.clear();
        }
        return result;
    }
}

No comments:

Post a Comment