From fecfc3da14dc8b565ddc1117eba56cbd4a92a01b Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Sun, 6 Aug 2023 05:54:51 -0700 Subject: [PATCH] group anagram started, used valid anagram for method --- Top150Interview/49_Group_Anagrams.py | 41 ++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/Top150Interview/49_Group_Anagrams.py b/Top150Interview/49_Group_Anagrams.py index 0b57f82..15d5e4d 100644 --- a/Top150Interview/49_Group_Anagrams.py +++ b/Top150Interview/49_Group_Anagrams.py @@ -1,5 +1,42 @@ -def groupAnagrams(self, strs): +def validAnagram(s: str, t: str) -> bool: + seen = {} + check = {} + count = 0 + for letter in s: + if letter in seen: + seen[letter] += 1 + else: + seen[letter] = 1 + for letter in t: + if letter in check: + check[letter] += 1 + else: + check[letter] = 1 + if seen != check: + return False + else: + return True + + +def groupAnagrams(strs: list[str])->list[str]: """ :type strs: List[str] :rtype: List[List[str]] - """ \ No newline at end of file + """ + grouped = [] + # Fill first list with matching anagrams + for i in range(len(strs)): + for j in range(i+1, len(strs)): + if validAnagram(strs[i], strs[j]) == True: + if i in grouped: + if j in grouped: + grouped.append(strs[j]) + else: + grouped.append(strs[i]) + + + return grouped + + + +print(groupAnagrams(["eat","tea","tan","ate","nat","bat"])) \ No newline at end of file