版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/88412661
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
题目链接:https://leetcode.com/problems/group-anagrams/
题目分析:hashmap
11ms,时间击败99.1%
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> mp = new HashMap<>();
for (String str : strs) {
char[] s = str.toCharArray();
Arrays.sort(s);
String key = new String(s);
if (!mp.containsKey(key)) {
mp.put(key, new ArrayList<String>());
}
mp.get(key).add(str);
}
List<List<String>> ans = new ArrayList<>();
for (List<String> list : mp.values()) {
ans.add(list);
}
return ans;
}
}