Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
思路:简单的dfs题目,遍历所有情况即可。
注意事项:StringBuffer,而不是BufferString。 另外要注意String a[]={“”,“”} 可以静态初始化; StringBuffer的deleteCharAt可以删除指定位置字符;String访问字符,charAt
另外注意询问:当输入为1时,输出? 0时输出? 以及“”时输出? 这个要考虑。。本题目的解答分别对应“”,“”,“”
- String digits_map[] ={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
- List<String> result = new ArrayList<String>();
- StringBuffer cur = new StringBuffer();
- public void helper(String digits,int start,int n) {
- if(start == n) {
- result.add(new String(cur));
- return;
- }
- char cchar = digits.charAt(start);
- String str = digits_map[cchar-'0'];
- for(int i=0;i< str.length();i++) {
- cur.append(str.charAt(i));
- helper(digits,start+1,n);
- cur.deleteCharAt(cur.length()-1);
- }
- }
- public List<String> letterCombinations(String digits) {
- if(digits==null) return result;
- int dlen = digits.length();
- if(dlen==0) {
- result.add(digits);
- return result;
- }
- helper(digits,0,dlen);
- return result;
- }