Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class{ public List<String> letterCombinations(String digits){ LinkedList<String> answer = new LinkedList<String>(); if (digits.isEmpty()) return answer; String[] mapping = new String[]{" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; answer.add(""); for(int i=0; i<digits.length(); i++){ String s = mapping[Character.getNumericValue(digits.charAt(i))]; while(answer.peek().length() < i+1){ String t = answer.remove(); for(char c: s.toCharArray()){ answer.add(t+c); } } } return answer; } }
Using a queue, every time fetch the fisrt queue and find if it’s length equals to the current processing number. if it’s small, adding the distinct characters of the current processing number’s coresponding Letters.
近期评论