problem:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters is just like on the telephone buttons.
Example:
Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Analysis:
This problem is pretty much like a recursive problem. We can use dfs to solve it. First of all I would draw the tree. Then write the code directly.
Here are something we should notice:
string本身是不可改变的,它只能赋值一次,每一次内容发生改变,都会生成一个新的对象,然后原有的对象引用新的对象,而每一次生成新对象都会对系统性能产生影响,这会降低.NET编译器的工作效率.
StringBuilder类则不同,每次操作都是对自身对象进行操作,而不是生成新的对象,其所占空间会随着内容的增加而扩充,这样,在做大量的修改操作时,不会因生成大量匿名对象而影响系统性能
public static List<String> letterCombinations1(String digits) {
// corner case
if (digits.length() == 0 || digits == null) {
return null;
}
// first build the result
List<String> res = new LinkedList<>();
// String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
HashMap<Integer, String> map = new HashMap<>();
map.put(0, "");
map.put(1, "");
map.put(2, "abc");
map.put(3, "def");
map.put(4, "ghi");
map.put(5, "jkl");
map.put(6, "mno");
map.put(7, "qprs");
map.put(8, "tuv");
map.put(9, "wxyz");
StringBuilder temp = new StringBuilder();
dfs(res, map, temp, 0, digits);
return res;
}
public static void dfs(List<String> res, HashMap<Integer, String> map, StringBuilder temp, int layer, String digits ) {
// basic case
if (layer == digits.length()) {
res.add(temp.toString());
return;
}
// find the first digit
int x = digits.charAt(layer) - '0';
String value = map.get(x);
for (int i=0; i<value.length(); i++) {
// add the first char into stringBuilder
temp.append(value.charAt(i));
dfs(res, map, temp, layer+1, digits);
temp.deleteCharAt(temp.length() - 1);
}
}