首页 > 代码库 > LeetCode 17 Letter Combinations of a Phone Number (电话号码字符组合)

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

https://discuss.leetcode.com/topic/8465/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 (电话号码字符组合)