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"].
题意:一个有数字组成的字符串,按照手机上数字所对应的字符串,输出所有可以出现的组合。字符串中的顺序由小到大
解题思路:这是动态累加的程序。如果说,"23",我先求出2的组合,然后将2的组合与3中所对应的所有字符一一组合,这显而易见。那如果是"234"呢。那之前有已经求出了23的所有组合,接下来,只要将23组合和4中的每个字符一一组合就可以了。同理类推,递归原理。
public static List<String> letterCombinations(String digits) { List<String> list=new ArrayList<String>(); List<String> res=new ArrayList<String>(); int len=digits.length(); if(len==0)return res; char ch; String tmp=null; for(int i=0;i<len;i++) { ch=digits.charAt(i); if(ch!=‘0‘&&ch!=‘1‘) { tmp=digit2String(ch); list.add(tmp); } } len=list.size(); for(int i=0;i<len;i++) { res=mergeListAndString(res,list.get(i)); } return res; } static List<String> mergeListAndString(List<String> list,String str) { if(str==null)return list; List<String> resTmp=new ArrayList<String>(); if(list.size()==0) { for(int i=0;i<str.length();i++) list.add(String.valueOf(str.charAt(i))); return list; }else { for(int j=0;j<str.length();j++) { for(int k=0;k<list.size();k++) { resTmp.add(str.charAt(j)+list.get(k)); } } return resTmp; } } static String digit2String(char ch) { String str=null; switch(ch) { case ‘2‘:str="abc";break; case ‘3‘:str="def";break; case ‘4‘:str="ghi";break; case ‘5‘:str="jkl";break; case ‘6‘:str="mno";break; case ‘7‘:str="pqrs";break; case ‘8‘:str="tuv";break; case ‘9‘:str="wxyz";break; default: str=null;break; } return str; }
这是第一版代码,虽然通过了。但是代码很长。接下来,看看有没有办法精简一下。
public static List<String> letterCombinations(String digits) { String[] digits2String={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; List<String> res=new ArrayList<String>(); int len=digits.length(); if(len==0)return res; char ch; String tmp=null; for(int i=0;i<len;i++) { ch=digits.charAt(i); if(ch<=‘9‘&&ch>‘1‘) { tmp=digits2String[ch-‘0‘]; res=mergeListAndString(res,tmp); } } return res; } static List<String> mergeListAndString(List<String> list,String str) { if(str==null)return list; List<String> resTmp=new ArrayList<String>(); if(list.size()==0) { for(int i=0;i<str.length();i++) list.add(String.valueOf(str.charAt(i))); return list; }else { for(int j=0;j<list.size();j++) { for(int k=0;k<str.length();k++) { resTmp.add(list.get(j)+str.charAt(k)); } } return resTmp; } }
时间: 2025-01-06 19:21:06