首页 > 其他 > 详细

Jan 15 - Letter Combination of Phone Number; BackTracing; Recursion; String

时间:2016-01-16 07:30:35      阅读:93      评论:0      收藏:0      [点我收藏+]

思路 参数里调用上一个list 读取出来 再加上新的letter组成新的string加入到新的list中,最后返回新的list

代码:

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<>();
        for(int i = 0; i < digits.length(); i++){
            char c = digits.charAt(i);
            list = addLetter(list, c);
        }
        return list;
        
    }
    
    public List<String> addLetter(List<String> list, char c){
        if(c == ‘1‘ || c == ‘0‘) return list;
        int len = list.size();
        List<String> newList = new ArrayList<>();
        int i = (int) (c - ‘2‘);
        if(len == 0){
            if(i>=0 && i<=4){
                for(int j = 0; j < 3; j++){
                    char ch = (char) (‘a‘+3*i+j);
                    newList.add(""+ch);
                }
            }
            else if(i == 5){
                newList.add(""+ ‘p‘);
                newList.add(""+ ‘q‘);
                newList.add(""+ ‘r‘);
                newList.add(""+ ‘s‘);
            }
            else if(i == 6){
                newList.add(""+ ‘t‘);
                newList.add(""+ ‘u‘);
                newList.add(""+ ‘v‘);
            }
            else{
                newList.add(""+ ‘w‘);
                newList.add(""+ ‘x‘);
                newList.add(""+ ‘y‘);
                newList.add(""+ ‘z‘);
            }
            return newList;
        }
        for(int k = 0; k < len; k++){
            String s = list.get(k);
            if(i>=0 && i<=4){
                for(int j = 0; j < 3; j++){
                    char ch = (char) (‘a‘+3*i+j);
                    newList.add(s+ch);
                }
            }
            else if(i == 5){
                newList.add(s+ ‘p‘);
                newList.add(s+ ‘q‘);
                newList.add(s+ ‘r‘);
                newList.add(s+ ‘s‘);
            }
            else if(i == 6){
                newList.add(s+ ‘t‘);
                newList.add(s+ ‘u‘);
                newList.add(s+ ‘v‘);
            }
            else{
                newList.add(s+ ‘w‘);
                newList.add(s+ ‘x‘);
                newList.add(s+ ‘y‘);
                newList.add(s+ ‘z‘);
            }
        }
        return newList;
    }
}

  

Jan 15 - Letter Combination of Phone Number; BackTracing; Recursion; String

原文:http://www.cnblogs.com/5683yue/p/5134871.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!