O(m*nlogn) solution
This commit is contained in:
parent
4e83f1d5ea
commit
5551dcc4fe
@ -1,50 +1,21 @@
|
||||
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]]
|
||||
"""
|
||||
final = []
|
||||
seen = []
|
||||
# Fill first list with matching anagrams
|
||||
for i in range(len(strs)):
|
||||
grouped = []
|
||||
print(f'i is: {strs[i]}')
|
||||
if i == len(strs)-1 and strs[i] not in grouped:
|
||||
grouped.append(strs[i])
|
||||
for j in range(i+1, len(strs)):
|
||||
print(f'j is: {strs[j]}')
|
||||
if validAnagram(strs[i], strs[j]) == True:
|
||||
if strs[i] not in grouped and strs[i] not in seen:
|
||||
grouped.append(strs[i])
|
||||
seen.append(strs[i])
|
||||
if strs[j] not in grouped and strs[j] not in seen:
|
||||
grouped.append(strs[j])
|
||||
seen.append(strs[j])
|
||||
if grouped:
|
||||
final.append(grouped)
|
||||
strs_table = {}
|
||||
|
||||
return final
|
||||
for string in strs:
|
||||
sorted_string = ''.join(sorted(string))
|
||||
|
||||
if sorted_string not in strs_table:
|
||||
strs_table[sorted_string] = []
|
||||
|
||||
strs_table[sorted_string].append(string)
|
||||
|
||||
return list(strs_table.values())
|
||||
|
||||
|
||||
|
||||
print(groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
|
||||
# print(groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
|
||||
print(groupAnagrams(["",""]))
|
||||
Loading…
Reference in New Issue
Block a user