-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLetterCombinationsOfAPhoneNumber.java
More file actions
37 lines (31 loc) · 1.31 KB
/
LetterCombinationsOfAPhoneNumber.java
File metadata and controls
37 lines (31 loc) · 1.31 KB
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
package com.company;
import java.util.ArrayList;
import java.util.List;
public class LetterCombinationsOfAPhoneNumber {
public List<String> letterCombinations(String digits) {
//把table上的数字对应的字母列出来,当输入为2是,digits[2]就是2所对应的"abc"
String[] table = new String[]
{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> list = new ArrayList<>();
//index从0开始,即digits的第一个数字
letterCombinations(list, digits, "", 0, table);
return list;
}
private void letterCombinations(List<String> list, String digits,
String curr, int index, String[] table) {
//最后一层退出条件
if (index == digits.length()) {
if (curr.length() != 0)
list.add(curr);
return;
}
//找到数字对应的字符串
String temp = table[digits.charAt(index) - '0'];
for (int i = 0; i < temp.length(); i++) {
//每次循环把不同字符串加到当前curr之后
String next = curr + temp.charAt(i);
//进入下一层
letterCombinations(list, digits, next, index + 1, table);
}
}
}