zoukankan      html  css  js  c++  java
  • leetcode Letter Combinations of a Phone Number

    Given a digit string, 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.

    Input:Digit string "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.

    解法是递推,下一次的list就是当前list的string加上当前数字代表的字母。

     1 public class Solution {
     2     List<String> lastList=new ArrayList<>();
     3     String[] N2=new String[]{"a","b","c"};
     4     String[] N3=new String[]{"d","e","f"};
     5     String[] N4=new String[]{"g","h","i"};
     6     String[] N5=new String[]{"j","k","l"};
     7     String[] N6=new String[]{"m","n","o"};
     8     String[] N7=new String[]{"p","q","r","s"};
     9     String[] N8=new String[]{"t","u","v"};
    10     String[] N9=new String[]{"w","x","y","z"};
    11     
    12     public List<String> letterCombinations(String digits) {
    13         String[] num = null;
    14         if (digits.equals("")) {
    15             lastList.add("");
    16             return lastList;
    17         }
    18         for (int i = 0; i < digits.length(); i++) {
    19             
    20             switch (digits.charAt(i)) {
    21             case '2':
    22                 num=N2;
    23                 break;
    24             case '3':
    25                 num=N3;
    26                 break;
    27             case '4':
    28                 num=N4;
    29                 break;
    30             case '5':
    31                 num=N5;
    32                 break;
    33             case '6':
    34                 num=N6;
    35                 break;
    36             case '7':
    37                 num=N7;
    38                 break;
    39             case '8':
    40                 num=N8;
    41                 break;
    42             case '9':
    43                 num=N9;
    44                 break;
    45 
    46             }
    47             if (i==0) {
    48                 lastList.addAll(Arrays.asList(num));
    49                 continue;
    50             }
    51             List<String> nextList=new ArrayList<>();
    52             for (String string : lastList) {
    53                 for (String ss : num) {
    54                     nextList.add(string+ss);
    55                 }
    56             }
    57             lastList=nextList;
    58         }
    59         return lastList;
    60     }
    61    
    62 }
  • 相关阅读:
    four day (linux基础学习1)
    three day(网络基础)
    two day(操作系统)
    Oldboy One day(计算机基础)
    mybatis调用存储过程
    调用jiathis分享接口
    汉字转换拼音工具类
    Ajax前后台交互 返回普通格式和JSON格式
    Bootstrap与EasyUI入门
    MD5,sha1加密工具类
  • 原文地址:https://www.cnblogs.com/birdhack/p/4096000.html
Copyright © 2011-2022 走看看