Tuesday, July 29, 2014

[LeetCode] Letters 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.

Java code
 public List letterCombinations(String digits) {
      String[] letters = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        List prevList = new ArrayList();
        prevList.add("");
        
        for(int i = 0; i < digits.length(); i++){
            int digit = digits.charAt(i) - '0';
            List currList = new ArrayList();
            
            for(int j = 0; j < prevList.size(); j++){
                for(int t = 0; t < letters[digit].length(); t++){
                    currList.add(prevList.get(j)+letters[digit].substring(t, t+1));
                }
            }

            prevList.clear();
            prevList.addAll(currList);
        }
        
        return prevList;
     }

No comments:

Post a Comment