LeetCode 17 Letter Combinations of a Phone Number (电话号码字符组合)

Posted 伊甸一点

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 17 Letter Combinations of a Phone Number (电话号码字符组合)相关的知识,希望对你有一定的参考价值。

题目链接 https://leetcode.com/problems/letter-combinations-of-a-phone-number/?tab=Description

 

HashMap<Character, String> map = new HashMap<>();
        map.put(0, "0");
        map.put(1, "1");
        map.put(2, "abc");
        map.put(3, "def");
        map.put(4, "ghi");
        map.put(5, "jkl");
        map.put(6, "mno");
        map.put(7, "pqrs");
        map.put(8, "tuv");
        map.put(9, "wxyz");

My java solution with FIFO queue

 
public List<String> letterCombinations(String digits) {
    LinkedList<String> ans = new LinkedList<String>();
    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;
}

 

 

参考代码:

 

package leetcode_50;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/***
 * 
 * @author pengfei_zheng
 * 优先队列使用
 */
public class Solution17 {
    public List<String> letterCombinations(String digits) {
        
        LinkedList<String> ans = new LinkedList<String>();
        if(digits == null || digits.length() == 0){
            return ans;
        }
        HashMap<Character, String> map = new HashMap<>();
        map.put(‘0‘, "0");
        map.put(‘1‘, "1");
        map.put(‘2‘, "abc");
        map.put(‘3‘, "def");
        map.put(‘4‘, "ghi");
        map.put(‘5‘, "jkl");
        map.put(‘6‘, "mno");
        map.put(‘7‘, "pqrs");
        map.put(‘8‘, "tuv");
        map.put(‘9‘, "wxyz");
        ans.add("");
        for(int i =0; i<digits.length();i++){
            char key = digits.charAt(i);
            while(ans.peek().length()==i){//遍历直到达到电话号码长度时结束
                String t = ans.remove();//移除旧的ans值
                for(char s : map.get(key).toCharArray())
                    ans.add(t+s);//添加新的ans
            }
        }
        return ans;
    }
}

 

以上是关于LeetCode 17 Letter Combinations of a Phone Number (电话号码字符组合)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题python解法:17. Letter Combinations of a Phone Number

Leetcode 17.——Letter Combinations of a Phone Number

LeetCode-17-Letter Combinations of a Phone Number

LeetCode17. Letter Combinations of a Phone Number

LeetCode17:Letter Combinations of a Phone Number

[LeetCode] 17. Letter Combinations of a Phone Number