电话号码组合 hash表
题目:
思路:
1 将数字和字母的对应 放入hash表 key 存数字,value 存数字对应的字母
2 使用队列 先将一个数字对应的字符入队, 出队跟下一个字符逐个匹配链接,再入队
(一)代码
class Solution { public List<String> letterCombinations(String digits) { if(digits == null){ return new ArrayList<>(); } //保存电话号码的字母 HashMap<Character,String[]> map = new HashMap<>(); map.put('2',new String[]{"a","b","c"}); map.put('3',new String[]{"d","e","f"}); map.put('4',new String[]{"g","h","i"}); map.put('5',new String[]{"j","k","l"}); map.put('6',new String[]{"m","n","o"}); map.put('7',new String[]{"p","q","r","s"}); map.put('8',new String[]{"t","u","v"}); map.put('9',new String[]{"w","x","y","z"}); List<String> res = new ArrayList<>(); Queue<String> queue = new LinkedList<>(); for(int i = 0 ; i < digits.length() ; i++){ help(map.get(digits.charAt(i)),queue); } for(String str : queue){ res.add(str); } return res; } public void help(String[] str,Queue<String> queue){ if(queue.size() == 0){ Stream.of(str).forEach(s -> { queue.offer(s); }); }else{ //保存队列大小 int size = queue.size(); for(int j = 0 ; j < size ; j++){ //出队 String queuestr = queue.poll(); for(int i = 0 ; i < str.length ; i++){ //拼接后入队 queue.offer(queuestr+str[i]); } } } } }
贪心