1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| public class Solution_0006 {
public static Map<Character, String[]> map = new HashMap<>();
static { map.put('2', new String[]{"a", "b", "c"}); map.put('3', new String[]{"d", "e", "f"}); map.put('4', new String[]{"g", "h", "i"}); map.put('5', new String[]{"j", "k", "l"}); map.put('6', new String[]{"m", "n", "o"}); map.put('7', new String[]{"p", "q", "r", "s"}); map.put('8', new String[]{"t", "u", "v"}); map.put('9', new String[]{"w", "x", "y", "z"}); }
public static List<String> getLetterList(List<String> result, String digits){
if(digits.length() == 0){ return result; }
if(result.size() == 0){
for (int i = 0; i < map.get(digits.charAt(0)).length; i++) { result.add(i, map.get(digits.charAt(0))[i]); } } else {
int size = result.size();
for (int i = 0; i < map.get(digits.charAt(0)).length; i++) { for (int j = 0; j < size; j++) { if(j + i * size < size){ result.set(j + i * size, result.get(j) + map.get(digits.charAt(0))[i]); } else{ result.add(result.get(j).substring(0, result.get(j).length() - 1) + map.get(digits.charAt(0))[i]); } } } }
result = getLetterList(result, digits.substring(1));
return result; }
public static List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
return getLetterList(result, digits); }
public static void main(String[] args) {
String digits = "23";
List<String> result = letterCombinations(digits);
for (String s : result) { System.out.println(s); } } }
|