Leetcode
49. Group Anagrams
Leeter
2021. 10. 22. 15:27
Description:
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.
'''
[1] hash function design)
idea::
hashmap -> sorted(str) : list()
key is sorted string. if sorted string is equal to the other string, value(original string) is appended to that list
code::
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashmap={}
for string in strs:
key=''.join(sorted(string))
if key in hashmap:
hashmap[key].append(string)
else:
hashmap[key]=[string]
answer=[]
for group in hashmap.values():
answer.append(group)
return answer
-T/C: O(n*mlogm), n==len(strs), m==max(len(str)) /str is in strs/
-S/C: O(n)
'''
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashmap={}
for string in strs:
key=''.join(sorted(string))
if key in hashmap:
hashmap[key].append(string)
else:
hashmap[key]=[string]
answer=[]
for group in hashmap.values():
answer.append(group)
return answer