Problem Solving/LeetCode

[LeetCode] 49. Group Anagrams

kimdozzi 2023. 8. 10. 21:03

https://leetcode.com/problems/group-anagrams/description/

 

Group Anagrams - LeetCode

Can you solve this real interview question? Group Anagrams - 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

leetcode.com

 

 

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        hm = defaultdict(list)
        for word in strs :
            hm["".join(sorted(word))].append(word)
        return list(hm.values())

파이썬에서 사전순으로 문자열 정렬하기

a = ['da', 'ef', 'ba']
a.sort()
print(a) 

# ['ba', 'da', 'ef']

리스트에서 해당 문자열 자체를 정렬하고 싶다면

s = "bqab"

s1 = s.sort() # str type에는 sort()라는 메소드가 없다. (String의 경우 첫글자의
							# 주소값으로 참조를 하기에 원본이 변경되면 안된다.)
s2 = sorted(s) # ['a', 'b', 'b', 'q'] => return type -> list
s3 = ''.joint(sorted(s)) # "abbq"