首页 > 代码库 > leetcode Letter Combinations of a Phone Number
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 }
leetcode Letter Combinations of a Phone Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。