17. Letter Combinations of a Phone Number
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
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"].
参考了官方答案后给出的代码(重点是维护一个队列):
class Solution {
public List<String> letterCombinations(String digits) {
String[] baseLetter= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> letterCombinations=new ArrayList<String>();
if(digits!=null&&!digits.equals(""))
{
letterCombinations.add("");
for(int i=0;i<digits.length();i++)
{
int index=digits.charAt(i)-'0';
while(letterCombinations.get(0).length()==i)
{
String head=letterCombinations.get(0);
letterCombinations.remove(0);
for(char t:baseLetter[index].toCharArray())
{
letterCombinations.add(head+t);
}
}
}
}
return letterCombinations;
}
}
更多推荐
所有评论(0)