49. Group Anagrams

2021. 10. 22. 15:27Leetcode

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

'Leetcode' 카테고리의 다른 글

25. Reverse Nodes in k-Group  (0) 2021.10.22
160. Intersection of Two Linked Lists  (0) 2021.10.22
451. Sort Characters By Frequency  (0) 2021.10.22
1208. Get Equal Substrings Within Budget  (0) 2021.10.21
56. Merge Intervals  (0) 2021.10.21