题目链接 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");

 
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;
    }
}

 

相关文章:

  • 2021-06-21
  • 2022-02-01
  • 2021-08-07
  • 2021-10-07
  • 2021-07-30
  • 2022-01-25
  • 2022-02-20
  • 2022-01-28
猜你喜欢
  • 2021-10-03
  • 2021-05-25
  • 2022-12-23
  • 2021-05-11
  • 2021-06-09
  • 2021-06-12
  • 2022-02-04
相关资源
相似解决方案