public class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> ans = new LinkedList<String>();
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if(digits.equals("")){
;
}else{
ans.add("");
for(int i =0; i<digits.length();i++){
int x = Character.getNumericValue(digits.charAt(i));
while(ans.peek().length()==i){
String t = ans.remove();
for(char s : mapping[x].toCharArray())
ans.add(t+s);
}
}
}
return ans;
}
}
我认为该题目的难点在于对于当前字符i,如何对后面的i+1字符的情况进行操作。这里就自然想到了队列这种数据结构。
例如:digits是23,那么将2代表的a取出,创建一个新的字符串将a与3所代表的字母赋值给该字符串,再进队列。循环该字符串的次数,即可。
判断何时停止取出?利用队列中字符串的长度与I这个指针所指向的位置比较进行判断。
这是我一开始看到这道题目所想到的思路。