This method harnesses the power of sorting and mapping to elegantly categorize anagrams. By iterating over each word in the provided list, it creates a sorted key that represents the word's characters in a uniform order. This key serves as a unique identifier for anagrams, allowing the method to accumulate words with identical keys into groups. Utilizing a Map to maintain these groups ensures that each collection of anagrams is easily retrievable and distinct. The method culminates by outputting these groups, showcasing the anagrams together in a clear and organized manner.
1classSolution{
2Anagrams(string_list) {
3let m = newMap();
4for (let i = 0; i < string_list.length; i++) {
5const key = string_list[i].split('').sort().join('');
67if (!m.has(key)) {
8 m.set(key, [string_list[i]]);
9 } else {
10const group = m.get(key);
11 group.push(string_list[i]);
12 m.set(key, group);
13 }
14 }
1516for (const group of m.values()) {
17console.log(group.join(' '));
18 }
19 }
20}
2122let s = new Solution();
23s.Anagrams(['act', 'god', 'cat', 'dog', 'tac']);
24