https://leetcode.com/problems/letter-combinations-of-a-phone-number/
这是我一开始的思路,穷举而已。
String[] myMap=new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
List<String> result=new ArrayList<String>();
int pointer=(int)Math.pow(4,digits.length());
if(pointer==1){return result;}
for(int i=0;i<pointer;i++){
String tmp="";
for(int j=0;j<digits.length();j++){
int index=3&(i>>j*2);
if(index>=myMap[digits.charAt(j)-'2'].length()){
tmp=null;
break;
}
tmp+=myMap[digits.charAt(j)-'2'].charAt(index);
}
if(tmp!=null){
result.add(tmp);
}
}
return result;
}
看到了一个别人用LinkedList完成的,觉得非常棒:
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"};
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;
}