首页 > 代码库 > [LeetCode]17 Letter Combinations of a Phone Number
[LeetCode]17 Letter Combinations of a Phone Number
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。