Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
- """ Step through the input, adding each word to a dict that has as
- its keys either a tuple with the count of each character or a sorted version of the string.
- """
- output_dict = dict()
- for word in strs:
- word_tuple = self._get_word_tuple(word) #str(sorted(word))
- if word_tuple not in output_dict:
- output_dict[word_tuple] = []
- output_dict[word_tuple].append(word)
- return list(output_dict.values())
- def _get_word_tuple(self, word: str) -> Tuple[str]:
- count_of_each_char = [0 for i in range(26)]
- for character in word:
- index_of_character = ord(character) - ord('a')
- count_of_each_char[index_of_character] += 1
- return tuple(count_of_each_char)
Advertisement
Add Comment
Please, Sign In to add comment