nathanwailes

LeetCode 49 - Group Anagrams - 2023.09.30 solution

Sep 30th, 2023
869
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. class Solution:
  2.     def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
  3.         """ Step through the input, adding each word to a dict that has as
  4.        its keys either a tuple with the count of each character or a sorted version of the string.
  5.        """
  6.         output_dict = dict()
  7.  
  8.         for word in strs:
  9.             word_tuple = self._get_word_tuple(word) #str(sorted(word))
  10.             if word_tuple not in output_dict:
  11.                 output_dict[word_tuple] = []
  12.             output_dict[word_tuple].append(word)
  13.        
  14.         return list(output_dict.values())
  15.  
  16.     def _get_word_tuple(self, word: str) -> Tuple[str]:
  17.         count_of_each_char = [0 for i in range(26)]
  18.         for character in word:
  19.             index_of_character = ord(character) - ord('a')
  20.             count_of_each_char[index_of_character] += 1
  21.         return tuple(count_of_each_char)
  22.  
Advertisement
Add Comment
Please, Sign In to add comment