Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
, Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
一刷
题解:
思路很简单,遍历字符串数组,将字符串变为char array, 然后sort, 变成统一的字符串,然后判断map中是否存在该字符串。这里要注意几个字符串和char array互相转换的函数
Time Complexity - O(n * mlogm) , Space Complexity - O(m * n), m为字符串的平均长度
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
if (strs == null) return res;
Map<String, List<String>> map = new HashMap<>();
for(String s:strs){
char[] sArr = s.toCharArray();
Arrays.sort(sArr);
String key = String.valueOf(sArr);
if(!map.containsKey(key)) map.put(key, new ArrayList<String>());
map.get(key).add(s);
}
return new ArrayList<>(map.values());
}
}