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.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]Example 2:
Input: strs = [""] Output: [[""]]Example 3:
Input: strs = ["a"] Output: [["a"]]
Constraints:
1 <= strs.length <= 1040 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
- Time complexity:
- Space complexity:
Let's break down how the code works:
The code defines a class named
Solutionthat contains a methodgroupAnagrams. The method takes a parameterstrs, which is a list of strings, and returns a list of lists of strings.It initializes a
defaultdictnamedresusing thecollectionsmodule. This dictionary-like object will automatically create an empty list as the default value for any key that does not exist.It iterates over each
wordin the input liststrs.For each
word, it creates acountlist of 26 integers initialized to 0. This list will be used to count the frequency of each character in the word.It iterates over each
charin the currentword.For each
char, it calculates the index by subtracting the ASCII value of "a" from the ASCII value of the current character using theord()function. This index represents the corresponding position in thecountlist.It increments the count at the calculated index by 1.
It converts the
countlist to a tuple and uses it as a key to access theresdictionary.It appends the current
wordto the list associated with the calculated key in theresdictionary.After iterating over all the words, it returns the values of the
resdictionary as the final result. The values are a list of lists, where each inner list contains anagrams grouped together.
count list, converts the list to a tuple, and uses it as a key to store the words in the res dictionary. Finally, it returns the grouped anagrams as a list of lists.
Comments
Post a Comment