zoukankan      html  css  js  c++  java
  • Keypad Permutation

    Problem

    Phone has letters on the number keys. for example, number 2 has ABC on it, number 3 has DEF, 4 number has GHI,... , and number 9 has WXYZ. Write a program that will print out all of the possible combination of those letters depending on the input.  

    Solution


    HashMap

     1 public static ArrayList<String> letterCombinations(String digits) {
     2   StringBuilder sb = new StringBuilder();
     3   ArrayList<String> res = new ArrayList<String>();
     4   
     5     if(digits == null) {
     6         return res;
     7     }
     8     
     9     //hashmap to store the key pad info
    10     Map<Character, char[]> hm = new HashMap<Character, char[]>();
    11     hm.put('2', new char[]{'a', 'b', 'c'});
    12     hm.put('3', new char[]{'d', 'e', 'f'});
    13     hm.put('4', new char[]{'g', 'h', 'i'});
    14     hm.put('5', new char[]{'j', 'k', 'l'});
    15     hm.put('6', new char[]{'m', 'n', 'o'});
    16     hm.put('7', new char[]{'p', 'q', 'r', 's'});
    17     hm.put('8', new char[]{'t', 'u', 'v'});
    18     hm.put('9', new char[]{'w', 'x', 'y', 'z'});
    19     
    20     helper(digits, res, sb, hm, 0);
    21     
    22     return res;
    23 
    24 }
    25 
    26 public static void helper(String digits, ArrayList<String> res, StringBuilder sb, Map<Character, char[]> hm, int pos) {
    27   if(pos == digits.length()) {
    28       res.add(sb.toString());
    29       return;
    30   }
    31   
    32   for(int i=0; i<hm.get(digits.charAt(pos)).length; i++) {
    33       sb.append(hm.get(digits.charAt(pos))[i]);
    34       helper(digits, res, sb, hm, pos+1);
    35       sb.deleteCharAt(sb.length()-1);
    36   }
    37 }
  • 相关阅读:
    02_Docker在CentOS 6和CentOS 7下的安装
    01_Docker概念简介、组件介绍、使用场景和命名空间
    nginx配置
    JavaScript高级 函数表达式 《JavaScript高级程序设计(第三版)》
    关于最近的一些事情
    3、《构》-3习题(6-9)
    关于叛逆的疑问和感想
    2、《构》-3习题(1-5)
    1、随笔+《构》-3
    svn 迁移至git操作手册
  • 原文地址:https://www.cnblogs.com/superbo/p/4112073.html
Copyright © 2011-2022 走看看