首页 > 代码库 > Group Anagrams

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"]
]
 1 public class Solution {
 2     public List<List<String>> groupAnagrams(String[] strs) {
 3         Map<String, List<String>> map = new HashMap<String, List<String>>();
 4         for(String str : strs){
 5             // 将单词按字母排序
 6             char[] carr = str.toCharArray();
 7             Arrays.sort(carr);
 8             String key = new String(carr);
 9             List<String> list = map.get(key);
10             if(list == null){
11                 list = new ArrayList<String>();
12             }
13             list.add(str);
14             map.put(key, list);
15         }
16         List<List<String>> res = new ArrayList<List<String>>();
17         // 将列表按单词排序
18         for(String key : map.keySet()){
19             List<String> curr = map.get(key);
20             Collections.sort(curr);
21             res.add(curr);
22         }
23         return res;
24     }
25 }

 

Group Anagrams