Letter Combinations of a Phone Number

题目地址:
https://leetcode.com/problems/letter-combinations-of-a-phone-number/#/description

题目:
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.

解题思路:
用map来存index和相应的数字。然后把每一个"abc" 加进去rst这个List<String>,然后就是一层一层加进去。

代码:

public List<String> letterCombinations(String digits) {
    String[] map = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    List<String> rst = new LinkedList<String>();
    if(digits.length() == 0){
        return rst;
    }
    rst.add("");
    for(int i = 0; i <= digits.length() - 1; i++){
        String temp = map[digits.charAt(i) - '0'];
        rst = combine(temp, rst);
    }
    return rst;
}
private List<String> combine(String temp, List<String> rst) {
    List<String> list = new ArrayList<>();
    for(String s : rst){
        for(int i = 0; i <= temp.length() - 1; i++){
            list.add(s + temp.charAt(i));
        }
    }
    return list;
}



Comments

Popular Posts