LeetCode-Letter Combinations of a Phone Number

Posted by mapoto4 on 2018-01-02

题目

Letter Combinations of a Phone Number

解题思路

1.建立映射表,对号码进行深度优先搜索。
2.找出对应的字母
3.StringBulider构建临时字符串

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
List<String> res;

public List<String> letterCombinations(String digits) {
String[] table = { " ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
StringBuilder tmp = new StringBuilder();

res = new LinkedList<String>();
helper(table, 0, tmp, digits);
return res;
}

private void helper(String[] table, int idx, StringBuilder tmp, String digits) {
if (idx == digits.length()) {
if (tmp.length() != 0)
res.add(tmp.toString());
} else {
String candidates = table[digits.charAt(idx) - '0'];
for (int i = 0; i < candidates.length(); i++) {
tmp.append(candidates.charAt(i));
helper(table, idx + 1, tmp, digits);
tmp.deleteCharAt(tmp.length() - 1);
}
}
}