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

[LeetCode]17 Letter Combinations of a Phone Number

时间:2015-01-02 16:13:14      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/

http://fisherlei.blogspot.com/2012/12/leetcode-letter-combinations-of-phone.html

public class Solution {
    public List<String> letterCombinations(String digits) {
        
        if (digits == null)
            return null;
            
        char[] chars = digits.toCharArray();

        List<List<String>> allMappings = new ArrayList<>();
        for (char c : chars)
        {
            List<String> mapping = getMapping(c);
            if (!mapping.isEmpty())
                allMappings.add(mapping);
        }
        
        // Use allMappings to generate results.
        Set<String> toReturn = new HashSet<>();
        toReturn.add("");
        for (List<String> mapping : allMappings)
        {
            Set<String> newSet = new HashSet<>();
            for (String oldstr : toReturn)
            {
                for (String s : mapping)
                {
                    newSet.add(oldstr + s);
                }
            }
            toReturn = newSet;
        }
        return new ArrayList<String>(toReturn);
    }
    
    private List<String> getMapping(char c)
    {
        List<String> toReturn = new ArrayList<>();
        if (c >= ‘2‘ && c <= ‘6‘)
        {
            for (int i = 0 ; i < 3 ; i ++)
            {
                char ch = (char)((c - ‘2‘) * 3 + ‘a‘ + i);
                toReturn.add(String.valueOf(ch));
            }
        }
        else if (c == ‘7‘)
        {
            toReturn.add("p");
            toReturn.add("q");
            toReturn.add("r");
            toReturn.add("s");
        }
        else if (c == ‘8‘)
        {
            toReturn.add("t");
            toReturn.add("u");
            toReturn.add("v");
        }
        else if (c == ‘9‘)
        {
            toReturn.add("w");
            toReturn.add("x");
            toReturn.add("y");
            toReturn.add("z");
        }
        return toReturn;
    }
}


[LeetCode]17 Letter Combinations of a Phone Number

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1598417

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