LC 17 Letter Combinations of a Phone Number(M)

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.

public List letterCombinations(String digits)

边界条件

解题思路 队列FIFO

采用队列,要入新产生的字符串,弹出之前的字符串。

public List<String> letterCombinations(String digits) {
    String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    LinkedList<String> res = new LinkedList<>();
    if(digits.length() <1)
        return res;
    // Initial
    res.add("");
    for(int i = 0; i<digits.length(); i++){
        int x = Character.getNumericValue(digits.charAt(i));
        //Still have old value need append new char
        while(res.peek().length() ==i){
            String temp = res.remove();
            for(char ch : mapping[x].toCharArray()){
                res.add(temp + ch);
            }
        }
    }
    return res;
}

Last updated

Was this helpful?