![](https://www.dazhuanlan.com/webchat.jpg)
Given an array of strings, group anagrams together.
Example
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
1 2 3 4 5
|
[ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
|
Note
- All inputs will be in lowercase.
- The order of your output does not matter.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> map = new HashMap<>();
for (String str: strs) { int[] dic = new int[26]; StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) dic[ch - 'a']++;
for (int i = 0; i < dic.length; i++) sb.append(dic[i]);
map.putIfAbsent(sb.toString(), new ArrayList<>()); map.get(sb.toString()).add(str); }
return new ArrayList<>(map.values()); }
|
近期评论