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; } }
作者: 伊甸一点
出处: http://www.cnblogs.com/zpfbuaa/
本文版权归作者伊甸一点所有,欢迎转载和商用(须保留此段声明),且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文链接 如有问题, 可邮件(zpflyfe@163.com)咨询.