码迷,mamicode.com
首页 > 其他好文 > 详细

17. Letter Combinations of a Phone Number

时间:2016-04-16 12:24:22      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 17. Letter Combinations of a Phone Number
     * 2015.11.30 by Mingyang 是对keyboard的循环
     * 1.长度标准:无
     * 2.可选的范围:数字对应的keyboard的string遍历每一个char
     * 3.往前走一步:加上这个char以后,index又加1
     * 4.后退一步:stringbuffer remove
     * 5.特别的case:长度相等
     * 6.关于重复:无
     */
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if (digits == null || digits.length() == 0)
            return result;
        String[] keyboard = { "", "", "abc", "def", "ghi", "jkl", "mno","pqrs", "tuv", "wxyz" };
        StringBuilder current = new StringBuilder();
        int index = 0;
        dfs(digits, index, current, keyboard, result);
        return result;
    }
    private void dfs(String digits, int index, StringBuilder current,String[] keyboard, List<String> result) {
        if (index == digits.length()) {
            result.add(current.toString());
            return;
        }
        int num = digits.charAt(index) - ‘0‘;// get integer number
        for (int i = 0; i < keyboard[num].length(); i++) {
            current.append(keyboard[num].charAt(i));
            dfs(digits, index + 1, current, keyboard, result);
            //这里注意一定不要写成++index,不然后面index还要减减
            current.deleteCharAt(current.length() - 1);
        }
    }

 

17. Letter Combinations of a Phone Number

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5397842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!