-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_anagrams.py
124 lines (96 loc) · 3.31 KB
/
group_anagrams.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
'''
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
'''
import string
def groupAnagrams(strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
'''
# Loop through the List[str] and group them 2 by 2
# for i in range (len(strs)):
# for j in range (i + 1, len(strs)):
# if isAnagram(strs[i], strs[j]):
# exists = False
# for k in range(len(tmp)):
# if [strs[i], strs[j]] in tmp[k]:
# exists = True
# break
# elif strs[i] in tmp[k]:
# tmp[k].append(strs[j])
# exists = True
# break
# elif strs[j] in tmp[k]:
# tmp[k].append(strs[i])
# exists = True
# break
# if not exists: tmp.append([strs[i], strs[j]])
# else:
# exists = False
# for k in range(len(tmp)):
# if strs[i] in tmp[k]:
# exists = True
# break
# if not exists: tmp.append([strs[i]])
'''
tmp = []
# If input contains only one string, then return that string ina List[List[str]]
if len(strs) == 1:
return [[strs[0]]]
# Loop through the List[str] and group them
for i in range(len(strs)):
found = False
for group in tmp:
if isAnagram(strs[i], group[0]):
group.append(strs[i])
found = True
break
if not found:
tmp.append([strs[i]])
# If tmp is empty, return [['']]
if len(tmp) == 0: return [['']]
return tmp
def groupAnagramsOptimized(strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
anagrams = {}
for word in strs:
sorted_word = ''.join(sorted(word))
if sorted_word in anagrams:
anagrams[sorted_word].append(word)
else:
anagrams[sorted_word] = [word]
return list(anagrams.values())
def isAnagram(s, t):
return sorted(s) == sorted(t)
# Some Test cases
if __name__ == "__main__":
# Examples
input = [
(["eat","tea","tan","ate","nat","bat"], [["bat"],["nat","tan"],["ate","eat","tea"]]),
([""], [[""]]),
(["a"], [["a"]])
]
for idx, (strs, expected) in enumerate(input):
print("\nExample", idx, ":")
print("Input:", strs)
print("Output:", groupAnagrams(strs))
print("Expected:", expected)