Skip to content

Instantly share code, notes, and snippets.

@aquawj
Last active October 29, 2017 00:36
Show Gist options
  • Save aquawj/4c049c35f51ca3c231ce6381c46f4e1c to your computer and use it in GitHub Desktop.
Save aquawj/4c049c35f51ca3c231ce6381c46f4e1c to your computer and use it in GitHub Desktop.
facebook
// 1. DFS
public class Solution {
String[] mapping = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; //比直接用map省空间,表示也简单
//注意将mapping设为全局变量,两个函数都要用
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if(digits == null || digits.length() == 0){
return res;
}
StringBuilder sb = new StringBuilder();
helper(digits, res, sb, 0);
return res;
}
//index为digits下标
public void helper(String digits, List<String> res, StringBuilder sb, int index){
if(sb.length() == digits.length()){ // 或 index == digits.length()
res.add(sb.toString()); //注意语法 sb.toString()
return;
}
String letters = mapping[digits.charAt(index) - '0'];//注意语法,[]内为char转int
for(int i = 0; i < letters.length(); i++){ //循环维度为letters长度
sb.append(letters.charAt(i)); //先加
helper(digits, res, sb, index+1);//操作下一个数字对应的leeters集
sb.deleteCharAt(sb.length() - 1); //再减
}
}
}
//优化:
//2. iteration (with queue)(non-recursion) 速度更快
public List<String> letterCombinations(String digits) {
List<String> ans = new LinkedList<String>(); //本质是queue
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ans.add("");//加一个空元素,否则后面无法peek和remove
for(int i =0; i<digits.length();i++){
int x = digits.charAt(i) - '0';
//以下为关键段
while(ans.peek().length()==i){ //每个上一数字对应字母(已在答案中的前缀字母)循环
String t = ans.remove(); //ans第一个元素(上一数字加入的候选字母)
for(char s : mapping[x].toCharArray()) //每个这一数字对应字母循环
ans.add(t+s); // 上一数字的字母 + 这一数字的字母
}
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment