您的位置:首页 > 其它

Leetcode 17 Letter Combinations of a Phone Number

2017-06-20 19:41 393 查看
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"].


Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

其实是一个排列组合的问题

比如说abcd的组合

先固定length 为1 的a(or b c d)

length为2的时候ab(or ac ad)。。

以此类推

public class Solution {
public List<String> letterCombinations(String digits) {
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
LinkedList<String> result = new LinkedList<String>();
if(digits == null || digits.length() == 0){
return result;
}
result.add("");
for(int i = 0; i < digits.length(); i++){
while(result.peek().length() == i){
String tmp = result.remove();
for(char c : mapping[digits.charAt(i) - '0'].toCharArray()){
result.offer(tmp + c);
}
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: