Given an array of strings, group anagrams together.
For example, given:
Return:
["eat", "tea", "tan", "ate", "nat", "bat"]
, Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
/*
Use a hashmap to gather anagrams, key is sorted string, value is a list that involves the original unsorted string which is same as the key after sorted.
time:O(Nklogk), space:O(N), N: the number of strings; k: the average length of strings.
*/
public class Solution {public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList<>();
if (strs == null || strs.length == 0) {
return ans;
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String newstr = String.valueOf(chars);
if (map.containsKey(newstr)) {
map.get(newstr).add(str);
} else {
List<String> list = new ArrayList<>();
list.add(str);
map.put(newstr, list);
}
}
for (List<String> list : map.values()) {
ans.add(list);
}
return ans;
}
}
No comments:
Post a Comment