0049 - Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Examples
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Input: strs = [""] Output: [[""]]
Input: strs = ["a"] Output: [["a"]]
Constraints
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
Java Solution
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List> result = new HashMap<String, List>();
for(String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = String.valueOf(chars);
if(!result.containsKey(key)) result.put(key, new ArrayList());
result.get(key).add(str);
}
return new ArrayList(result.values());
}
}
Last updated