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.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
import java.util.LinkedList;
import java.util.List;
public class Main {
public List letterCombinations(String digits) {
LinkedList ans = new LinkedList();
if (digits == null || digits.length() == 0) {
return ans;
}
String[] intToStringArray = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
int x, n = digits.length();
String s;
ans.add("");
for (int i = 0; i < n; i++) {
while (ans.peek().length() == i) {//当ans首结点长度为0时,把第一个数代表的字符依次加入链表,
// 当首结点长度为1时,需要进行下次循环,依次弹出首结点,首结点再与后面的数代表的每个字符累加,加入到链表中
// 此时首结点的长度为2,重复操作..........最后输出
s = ans.remove();//先获取链表的首结点赋值到s,再删除首结点,避免下次再循环到,下次需要用到新的首结点
x = Character.getNumericValue(digits.charAt(i));//char->int
for (char c : intToStringArray[x].toCharArray()) {//用弹出的首结点去累加后面的字符
ans.add(s + c);
}
}
}
return ans;
}//letterCombinations
public static void main(String[] args) {
System.out.println(new Main().letterCombinations("02"));//[0a, 0b, 0c]
System.out.println(new Main().letterCombinations("234"));//[adg, adh, adi, aeg, aeh, aei, afg, afh, afi, bdg, bdh, bdi,
// beg, beh, bei, bfg, bfh, bfi, cdg, cdh, cdi, ceg, ceh, cei, cfg, cfh, cfi]
// System.out.println(new Main().letterCombinations(""));
}
}
//peek是返回首结点的值,不删除首结点
//remove是返回首结点的值,删除首结点