您的位置:首页 > 其它

[LeetCode]17 Letter Combinations of a Phone Number

2015-01-02 13:42 435 查看
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