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 <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
- Time complexity:
- Space complexity:
Let's break down how the code works:
The code defines a class named
Solution
that 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
defaultdict
namedres
using thecollections
module. 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
word
in the input liststrs
.For each
word
, it creates acount
list 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
char
in 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 thecount
list.It increments the count at the calculated index by 1.
It converts the
count
list to a tuple and uses it as a key to access theres
dictionary.It appends the current
word
to the list associated with the calculated key in theres
dictionary.After iterating over all the words, it returns the values of the
res
dictionary 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