forked from super30admin/Hashing-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupanagrams.py
More file actions
42 lines (36 loc) · 1.44 KB
/
groupanagrams.py
File metadata and controls
42 lines (36 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
We wll take the string sort it and check if it is already ut in a hashmap, if not
we will put it in a hasmap and check if the other string encountered aligns with the string, if yes, we will put it as a value
of the sorted string in a hashmap. Finally we will print all the values
Time Complexity: O(nklogk)- where k is the length of the string and n is the input string size
space:O(n)
"""
class Solution:
def groupAnagrams(self, strs):
if strs==None or len(strs)==0:
return []
hashmap=dict()
for string in strs:
# print(string)
# string.split()
sortedString="".join(sorted(string))
print("the sorted string is", sortedString)
# ' '.join(sortedString)
# print(sortedString)
if not sortedString in hashmap.keys():
hashmap[sortedString]=[string]
# else:
# hashmap[sortedString] = [string]
else:
hashmap[sortedString].append(string)
# ### for the key there's an array list
# hashmap[sortedString]=string
# hashmap.get(sortedString)=string
# hashmap.get(sortedString)=string
return [hashmap.values()]
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(strs)
solve=Solution()
print(solve.groupAnagrams(strs))