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.

题目含义:将给定的一组字符串数组,按照同构词(相同字母组成的单词)分类,每组单词按照字典排序。

思路:将每个字符串升序排列,这样同构字符串排列后的顺序一致,可以作为map的key使用

 

 1     public List<List<String>> groupAnagrams(String[] strs) {
 2          Map<String,List<String>> stringMap = new HashMap<>();
 3         List<List<String>> result = new ArrayList<>();
 4         if (strs.length == 0) return result;
 5 
 6         for (String str:strs)
 7         {
 8             char[]chars = str.toCharArray();
 9             Arrays.sort(chars);
10             String newString = new String(chars);
11             List<String> strings = stringMap.getOrDefault(newString,new ArrayList<>());
12             strings.add(str);
13             stringMap.put(newString,strings);
14         }
15         return new ArrayList<>(stringMap.values());       
16     }

 

posted @ 2017-10-18 10:05  daniel456  阅读(89)  评论(0编辑  收藏  举报