class Solution {
public List
<List
<String
>> groupAnagrams
(String[] strs
) { List<List<String>> result = new ArrayList<>();
Map
<String, List
<String
>> map
= new HashMap
<>(); // iterating over each string from giver array of strings
{
// convert the current string to charArray, and store hash values
// suppose str is : "cat"
int[] count = new int[26];
for(char ch : str.toCharArray())
{
count[ch - 'a']++;
}
// count[0]=1 --> for 'a', count[2]=1 --> for 'c', count[19]=1 --> for 't'
// convert count array into string
StringBuilder sb = new StringBuilder();
for(int index : count)
{
// adding hashes in between the count of characters
sb.append("#").append(index);
}
// sb: "#1#0#1#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1#0#0#0#0#0#0"
// convert string builder to string
// key = "#1#0#1#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1#0#0#0#0#0#0"
if(!map.containsKey(key))
map.put(key, new ArrayList<String>());
// Always add the string to the list, whether the key is new or not.
// so suppose this key : {cat, act}, adding current string as anagram
map.get(key).add(str);
}
result.addAll(map.values());
return result;
}
}