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

LeetCode 49. Group Anagrams

时间:2017-09-15 10:13:45      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:null   ppi   lin   prime   toc   bat   string   list   nat   

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

标签:null   ppi   lin   prime   toc   bat   string   list   nat   

原文地址:http://www.cnblogs.com/hanhanhan93/p/7524335.html

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