题解 | #电话号码的字母组合#
电话号码的字母组合
http://www.nowcoder.com/practice/2d3a1e71112546ac836700ccbd1f5936
import java.util.*;
public class Solution {
public ArrayList<String> ans = new ArrayList<>();
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param num string字符串
* @return string字符串ArrayList
*/
public ArrayList<String> phoneNumber(String num) {
// write code here
HashMap<Character, ArrayList<Character>> hashMap = new HashMap<>();
int index = 0;
for (int i = 2; i <= 9; i++) {
ArrayList<Character> tmpArr = new ArrayList<>();
if (i == 7 || i == 9) {
for (int j = 0; j < 4; j++) {
tmpArr.add((char) ('A' + index));
index++;
}
} else {
for (int j = 0; j < 3; j++) {
tmpArr.add((char) ('A' + index));
index++;
}
}
hashMap.put((char) ('0' + i), tmpArr);
}
char[] nums = num.toCharArray();
process("", nums, 0, hashMap);
return ans;
}
public void process(String previousString, char[] nums, int index, HashMap<Character, ArrayList<Character>> hashMap) {
if (index >= nums.length) {
ans.add(new String(previousString));
return;
}
char currentChar = nums[index];
ArrayList<Character> chrs = hashMap.get(currentChar);
for (char chr : chrs) {
previousString += chr;
process(previousString, nums, index + 1, hashMap);
previousString = previousString.substring(0, previousString.length() - 1);
}
}
}