您的位置:首页 > 其它

(Leetcode)17. Letter Combinations of a Phone Number——使用LinkedList

2016-05-08 00:02 477 查看
题目: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”].

算法思想:

每读入一个新的数字 , 比如 5,获得该数字对应的字符串数组strs,5对应的是{“j”,”k”,”l”}。将 result中的每一项取出,在后面分别加上j/k/l,将这新的三项加入result,并删除原来的项。

代码:

public List<String> letterCombinations(String digits) {
LinkedList<String> result = new LinkedList<String>();
if(digits.equals(""))  return result;
result.add("");
String trans_function[][] = {
{"0"},                // 0
{"1"},                   // 1
{"a","b","c"},        // 2
{"d","e","f"},        // 3
{"g","h","i"},        // 4
{"j","k","l"},        // 5
{"m","n","o"},        // 6
{"p","q","r","s"},    // 7
{"t","u","v"},        // 8
{"w","x","y","z"}     // 9
};

for(int i=0 ; i<digits.length(); i++){
String strs[] = trans_function[digits.charAt(i)-'0'];

while( result.peek().length()==i ){
String head_str = result.remove();
for( String ch: strs ){
result.add(head_str+ch);
}
}
}

return result;
}


几个函数:

java.util.LinkedList:

双向列表,列表中的每个节点都包含了对前一个和后一个元素的引用.

peek()
Retrieves, but does not remove, the head (first element) of this list.
return :the head of this list, or null if this list is empty
remove()
Retrieves and removes the head (first element) of this list.
return : the head of this list
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode