Letter Combinations of a Phone Number

Given a mapping of digit to letters, just like the phone keyboard.

Given a string representing a typing of numbers, that is, it only contains digits, find all possible combinations of letters. We assume that there are only 26 lowercase letters in the keyboard, just shown in the picture.

e.g: "23" -> [ad, ae, af, bd, be, bf, cd, ce, cf]. "12" -> [a, b, c]

Solution:

1. build a mapping using a two dimension char array. arr[i] stands for the charset of number i and arr[i][j] stands for the jth letter of number i's charset.

2. Use backtracking to add combinations to the result list. We build a StringBuilder to temporarily store the string we build so far. Whenever its length equals the length of target digits string, we add its string value to the result list. If its length is less than the digits length, we find the charset of current digit, which can be index by the length of the StringBuilder.

3. for every letter in the charset, we add it to the StringBuilder first, recursively invoke this function and remove it from the StringBuilder for cleanness.

4. From the main function, we invoke this recursive method and return the final result.

Code:

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if(digits == null || digits.length()==0)
            return res;
        char[][] letters = {{' '},{' '},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},
                {'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
        StringBuilder temp = new StringBuilder();
        char[] arr = digits.toCharArray();
        addLetters(res, temp, letters, arr);
        return res;
    }
    private void addLetters(List<String> res, StringBuilder temp, char[][] letters, char[] digits){
        if(temp.length()==digits.length){
            res.add(temp.toString());
            return;
        }
        char[] curr = letters[digits[temp.length()]-'0'];
        for(int i = 0; i < curr.length; i++){
            temp.append(curr[i]);
            addLetters(res, temp, letters, digits);
            temp.deleteCharAt(temp.length()-1);
        }
    }
}
View Code

 

posted @ 2017-06-20 23:52  小风约定  阅读(53)  评论(0)    收藏  举报