zoukankan      html  css  js  c++  java
  • [leetcode]17. Letter Combinations of a Phone Number手机键盘的字母组合

    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

    A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

    Example:

    Input: "23"
    Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

    Note:

    Although the above answer is in lexicographical order, your answer could be in any order you want.

    题意:

    给定一个数字串,看看有多少种对应的字母串。

    思路:

    Assumption:

    字符串的合法性,是否包含1这个数字?如果包含,怎么处理?同样,输入是否考虑 * 或 #?

    空字符串怎么处理?

    多个解按什么顺序返回?

    High Level带着面试官walk through:

    take "23" for example:

    when index = 0,  pointing to '2' in "23"

    String letters  =  "abc"

    for each char in letters,

    add to path 

    move index forward, pointing to '3' in "23",  recursively call the helper function to add every char of "def" to the path

     

    code

     1 class Solution {
     2     private static String[] keyboard =
     3             new String[]{ " ", "", "abc", "def", // '0','1','2',...'9'
     4             "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
     5     
     6     public List<String> letterCombinations(String digits) { //"23"
     7         List<String> result = new ArrayList<>();
     8         if(digits.length() == 0 ) return result;
     9         helper(digits, 0, new StringBuilder(), result);
    10         return result;    
    11     }
    12     
    13     private void helper(String digits, int index, StringBuilder sb, List<String> result){
    14         if(index == digits.length()){
    15             result.add(sb.toString());
    16             return;
    17         }   
    18         String letters = keyboard[digits.charAt(index) - '0']; 
    19         for(int i = 0;  i < letters.length(); i++ ){
    20             char c = letters.charAt(i);
    21             sb.append(c);
    22             helper(digits, index+1, sb, result);
    23             sb.deleteCharAt(sb.length() - 1);
    24         }
    25     }
    26 }

    注意: 这个题也可以用String path来存每条路径。 可是我自己觉得用StringBuilder这么动态伸缩,更显得有“Backtracking”的味道。 

  • 相关阅读:
    【mysql+RBAC】RBAC权限处理(转载:http://www.cnblogs.com/xiaoxi/p/5889486.html 平凡希)
    【小程序】获取微信 自带的 收货地址获取和整理
    【TP3.2】跨库操作和跨域操作
    【JS】一款好用的JS日历选择插件【bootstrap-datetimepicker.js】
    Python 读写文件中w与wt, r与rt的区别
    Python 在序列上跟踪索引和值
    SoapUI 使用变量
    python 跳过可迭代对象的开始部分
    Python 迭代器切片
    Python: 类中为什么要定义__init__()方法
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9189741.html
Copyright © 2011-2022 走看看