(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”].
双向列表,列表中的每个节点都包含了对前一个和后一个元素的引用.
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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解