17. Letter Combinations of a Phone Number
一、题目
1、审题
2、分析:
给出数字组成的字符串,求他所对应电话号码中的字母所组成的字符串的集合。
二、解答
1、分析:
a、依次截取字符串中的数字,作为switch 语句的条件调用 case;
b、case 中将原 List 中所有字符串与数字对应的字母集合 List 进行全连接;
c、注意: ArrayList 中的元素依照放入顺序存放;故,连接后去除原 List 中的起始元素即为实现了全连接
class Solution { public List<String> letterCombinations(String digits) { int len = digits.length(); List<String> targetList = new ArrayList<String>(); if(len == 0) return targetList; int i = 0; while(i < len) { switch (digits.charAt(i++) - '0') { case 2: conbindString(targetList, Arrays.asList("a", "b", "c")); break; case 3: conbindString(targetList, new ArrayList<String>(Arrays.asList("d", "e", "f"))); break; case 4: conbindString(targetList, new ArrayList<String>(Arrays.asList("g", "h", "i"))); break; case 5: conbindString(targetList, new ArrayList<String>(Arrays.asList("j", "k", "l"))); break; case 6: conbindString(targetList, new ArrayList<String>(Arrays.asList("m", "n", "o"))); break; case 7: conbindString(targetList, new ArrayList<String>(Arrays.asList("p", "q", "r", "s"))); break; case 8: conbindString(targetList, new ArrayList<String>(Arrays.asList("t", "u", "v"))); break; case 9: conbindString(targetList, new ArrayList<String>(Arrays.asList("w", "x", "y", "z"))); break; default: break; } } return targetList; } public void conbindString(List<String> aList, List<String> bList) { int len = aList.size(); if(len == 0) { aList.addAll(bList); return; } for (int i = 0; i < len; i++) { String s = aList.get(0); for (int j = 0; j < bList.size(); j++) aList.add(s + bList.get(j)); aList.remove(0); } } }