题目描述
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.
算法1
时间复杂度 O(nmlog(m))
Java 代码
import java.util.*;
public class Solution {
List<List<String>> res = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
public List<List<String>> groupAnagrams(String[] strs) {
int n = strs.length;
if (n == 0) {
return res;
}
for (String str : strs) {
char[] strArr = str.toCharArray();
Arrays.sort(strArr);
String sortedStr = String.valueOf(strArr);
if (!map.contains(sortedStr)) {
map.put(sortedStr, new ArrayList<>());
}
map.get(sortedStr).add(str);
}
res.addAll(map.values());
return res;
}
}