LeetCode 49. Group Anagrams
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 49. Group Anagrams相关的知识,希望对你有一定的参考价值。
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
Answer:
1.using HashTable & Sort O(n*nlgn)
1 public List<List<String>> groupAnagrams(String[] strs) { 2 Map<String, List<String>> map = new HashMap<String, List<String>>(); 3 for (int i=0; i < strs.length; i++){ 4 String s = strs[i]; 5 char[] c = s.toCharArray(); 6 Arrays.sort(c); 7 String keyStr = String.valueOf(c); 8 if(map.containsKey(keyStr)){ 9 List<String> list = map.get(keyStr); 10 list.add(s); 11 map.put(keyStr, list); 12 } 13 else{ 14 List<String> list = new ArrayList<String>(); 15 list.add(s); 16 map.put(keyStr, list); 17 } 18 } 19 List<List<String>> result = new ArrayList<List<String>>(map.values()); 20 return result; 21 }
2. just using HashTable and a smart method to create the key
1 private static final int[] PRIMES = new int[]{2, 3, 5, 7, 11 ,13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 107}; 2 3 public List<String> anagrams(String[] strs) { 4 List<String> list = new LinkedList<>(); 5 Map<Integer, List<String>> mapString = new HashMap<>(); 6 int result = -1; 7 for (int i = 0; i < strs.length; i++){ 8 int mapping = 1; 9 for (int j = 0, max = strs[i].length(); j < max; j++) { 10 mapping *= PRIMES[strs[i].charAt(j) - ‘a‘]; 11 } 12 List<String> strings = mapString.get(mapping); 13 if (strings == null) { 14 strings = new LinkedList<>(); 15 mapString.put(mapping, strings); 16 } 17 strings.add(strs[i]); 18 } 19 for (List<String> mapList : mapString.values()){ 20 if (mapList.size() > 1) 21 list.addAll(mapList); 22 } 23 return list; 24 }
以上是关于LeetCode 49. Group Anagrams的主要内容,如果未能解决你的问题,请参考以下文章