LeetCode Letter Combinations of a Phone Number(017)解法总结

232 阅读1分钟

描述

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.

思路

使用队列的思想,在每读取到一个新的数字的时候,就将当前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.

这个问题考察了队列的应用,难度不大。