IncredibleThings

导航

Leetcode-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"].

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result=new ArrayList<String>();
        if(digits==null || digits.length()==0){
            return result;
        }
        List<String> list=new ArrayList<String>();
        for(int i=0; i<digits.length(); i++){
            char c=digits.charAt(i);
            if(c=='2'){
                list.add("abc");
            }
            else if(c=='3'){
                list.add("def");
            }
            else if(c=='4'){
                list.add("ghi");
            }
            else if(c=='5'){
                list.add("jkl");
            }
            else if(c=='6'){
                list.add("mno");
            }
            else if(c=='7'){
                list.add("pqrs");
            }
            else if(c=='8'){
                list.add("tuv");
            }
            else if(c=='9'){
                list.add("wxyz");
            }
        }
        StringBuilder sb=new StringBuilder();
        dfs(list, 0, sb, result);
        return result;
    }
    public void dfs(List<String> inputs, int step,StringBuilder sb,List<String> res){
        if(step==inputs.size()){
            res.add(sb.toString());
            return;
        }
        String str=inputs.get(step);
        for(int i=0; i<str.length(); i++){
            sb.append(str.charAt(i));
            dfs(inputs, step+1, sb, res);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}

  二刷,也可以用BFS来写:

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if(digits == null || digits.length() == 0){
            return res;
        }
        String[] strArr = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        //int len = digits.length();
        for(char c : digits.toCharArray()){
            List<String> temp = new ArrayList<>();
            for(char ac : strArr[c - '0'].toCharArray()){
                if(res.isEmpty()){
                    temp.add(""+ac);
                }
                else{
                    for(String str : res){
                        StringBuilder sb = new StringBuilder(str);
                        sb.append(ac);
                        temp.add(sb.toString());
                    }
                }
            }
            res = temp;
        }
        return res;
        
    }
    
}

 

posted on 2016-07-23 00:53  IncredibleThings  阅读(128)  评论(0编辑  收藏  举报