【LeetCode】Letter Combinations of a Phone Number

来源:互联网 发布:匡恩网络 工控安全 编辑:程序博客网 时间:2024/04/25 14:23

Letter Combinations of a Phone Number 
Total Accepted: 4387 Total Submissions: 17627 My Submissions
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,但是有一点需要注意,输入有可能为"",这个比较变态,感觉这个不应该是考点之一。
        将数字和字符的对应关系组成了一个数组
        String array[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        这样处理起来相对要方便些。特别要注意digits中为数字的再转换,否则的话继续。
Java AC

public class Solution {    public String array[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};    public ArrayList<String> letterCombinations(String digits) {        ArrayList<String> list = new ArrayList<String>();        if(digits == null){            return list;        }        char numArr[] = digits.toCharArray();        int len = digits.length();        StringBuffer sb = new StringBuffer();        dfs(list,sb,0,numArr,len);        return list;    }    public void dfs(ArrayList<String> list,StringBuffer sb,                int tempLen,char numArr[],int len){        if(tempLen == len){            list.add(sb.toString());            return;        }        if(numArr[tempLen] >= '0' && numArr[tempLen] <= '9' ){            String tempStr = array[numArr[tempLen] - '0'];            int strLen = tempStr.length();            for(int i = 0; i < strLen; i++){                StringBuffer newsb = new StringBuffer(sb);                newsb.append(String.valueOf(tempStr.charAt(i)));                dfs(list,newsb,tempLen+1,numArr,len);            }        }else{            StringBuffer newsb = new StringBuffer(sb);            newsb.append(String.valueOf(numArr[tempLen]));            dfs(list,newsb,tempLen+1,numArr,len);           }    }}
0 0
原创粉丝点击