标签: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