Imagine we have following list of strings:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
The output of our program should group each set of anagram and return them all together as a list as following:
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
My current solution finds the first set of anagrams but fails to detect the other two and instead, duplicates the first groups into the list:
class Solution(object):
def groupAnagrams(self, strs):
allResults=[]
results=[]
temp=''
for s in strs:
temp=s[1:]+s[:1]
for i in range(0,len(strs)):
if temp==strs[i]:
results.append(strs[i])
allResults.append(results)
return allResults
and the output is:
[["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"]]
How to fix this issue?
EDIT:
I have fixed the duplication in appending by appending the results
into allResults
outside of second loop:
class Solution(object):
def groupAnagrams(self, strs):
allResults=[]
results=[]
temp=''
for s in strs:
temp=s[1:]+s[:1]
for i in range(0,len(strs)):
if temp==strs[i]:
results.append(strs[i])
allResults.append(results)
print(results)
return allResults
Yet, it does not detect the other two sets of anagrams.
See Question&Answers more detail:
os