LeetCode Letter Combinations of a Phone Number(017)解法總結

NewCoder1024發表於2020-03-27

描述

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.

LeetCode Letter Combinations of a Phone Number(017)解法總結

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.

思路

使用佇列的思想,在每讀取到一個新的數字的時候,就將當前list中的所有內容取出,並所有加上當前數字可能對應的字元。

class Solution {
    public List<String> letterCombinations(String digits) {
        
        //將數字和可能的字元對應起來,對應關係為:數字 - 2 = 字串下標
        String buttons[] = new String[]{
            "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
        };
        //定義StringBuffer和String陣列
        LinkedList<StringBuffer> out = new LinkedList<StringBuffer>();
        LinkedList<String> fin = new LinkedList<String>();
        if(digits.length() == 0){
            return fin;
        }
        //加入空白Buffer,啟動迴圈
        out.add(new StringBuffer(""));
        //遍歷輸入的數字
        for(int i = 0; i<digits.length(); i++){
            int count = out.size();
            //遍歷當前list中的所有情況
            while(count != 0){
                StringBuffer cur_buff = out.getFirst();
                out.removeFirst();
                //將list中的每種情況都與輸入數字對應的多種可能性組合
                for(int j = 0;j<buttons[digits.charAt(i) - '2'].length();j++){
                    cur_buff.append(buttons[digits.charAt(i) - '2'].charAt(j));
                    StringBuffer new_buff = new StringBuffer(cur_buff);
                    out.add(new_buff);
                    cur_buff.deleteCharAt(cur_buff.length() - 1);
                }
                count --;
            }
        }
        //轉化為可以接受的輸出格式
        for(int i = 0;i<out.size();i++){
            fin.add(out.get(i).toString());
        }
        return fin;
    }
}複製程式碼
Runtime: 1 ms, faster than 78.39% of Java online submissions for Letter Combinations of a Phone Number.
Memory Usage: 38.6 MB, less than 6.16% of Java online submissions for Letter Combinations of a Phone Number.

這個問題考察了佇列的應用,難度不大。

相關文章