您的位置:首页 > 其它

leetcode-17. Letter Combinations of a Phone Number

2017-06-10 20:15 369 查看
https://leetcode.com/problems/letter-combinations-of-a-phone-number/#/description

问题描述:



Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].


思路解析:

将每个按键代表的字符串映射到一个string数组当中,下标对应着按键的顺序。将组合的结果存到LinkedList当中,模拟FIFO队列,每次取出队头元素,然后和其他按键的元素进行组合。

代码如下:

public class Solution {
public List<String> letterCombinations(String digits) {

LinkedList<String> result=new LinkedList<String>();

if(digits.length()==0) return result;

String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

result.add("");

for(int i=0;i<digits.length();i++)
{
int k=Character.getNumericValue(digits.charAt(i));

while(result.peek().length()==i){

String t=result.remove();

for(char s:mapping[k].toCharArray())
{
result.add(t+s);
}

}

}
return result;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string leetcode