LeetCode(17)-Letter Combinations of a Phone Number
17.Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.Example:
Input: “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.
這個題的大概意思是:給一個一串數字的字串(2~9),然後裡面的數字代表手機9鍵中的鍵盤,
每一個鍵中都有對應的字母,然後要求輸出所有的字母組合。
這個題考的就是數學中的排列組合,這裡講一下LeeCode上投票最多的一個解法,挺棒的。
先貼出程式碼吧
public List<String> letterCombinations(String digits) {
LinkedList<String> ans = new LinkedList<String>();
if(digits.isEmpty()) return ans;
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ans. add("");
for(int i =0; i<digits.length();i++){
int x = Character.getNumericValue(digits.charAt(i));
while(ans.peek().length()==i){
String t = ans.remove();
for(char s : mapping[x].toCharArray())
ans.add(t+s);
}
}
return ans;
}
-
大致思路如下:
-
我們以題目給的例子來進行單步除錯,首先建立一個LinedList作為一個佇列,然後建立一個String數字將數字與字母
相對映。 -
先看最外層的的迴圈,這層迴圈就是“遍歷按鍵”,然後將按鍵中的字母依次放入佇列中
我們將這裡的LindList理解為佇列,事實上LinedList實現了Queue介面)
) -
放入後跳出while迴圈
-
進入外層for迴圈的第二重,這裡就比較關鍵了,這裡我們來仔細研究一下
- 此時i=1,i表示的是佇列中每個元素的長度。
- while迴圈的條件是佇列中“對頭”的元素長度等於i,此時佇列頭元素為“a”長度為1,
String t = ans.remove();
- 這行語句實際上有2個操作,先將對頭的元素出隊,然後複製給t,然後我們接著看這段程式碼
for(char s : mapping[x].toCharArray())
ans.add(t+s);
- 首先是遍歷第二個按鍵中的字母然後與t進行組合,然後依次加入隊尾
- 然後此重迴圈結束後,進入外層for迴圈的下一重,大致就是這樣
- b出隊,然後將下一個按鍵對應的字母一直組合
- c出隊 ··
- 就這樣實現了所有的組合