문제 URL : https://leetcode.com/problems/group-anagrams/
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
문제 접근법 : 그룹으로된 anagrams의 문자열을 찾는문제인데
해당 문자열 이주어젔을때 동일한 문자열로만 구성되어있다면
abc ,bca 는 동일한 anagram 이라고 표현합니다. abc로 구성되어있으니
결국엔 map을 이용하여 문자열을 정렬후 key값을 정렬된 key로 받아들이고
value값을 리스트,혹은 벡터로 저장후
최종적으로 map의 key값안에있는것을 전부 answer에 담아서 리턴해주면됩니다.
소스코드:
from collections import Counter
class Solution(object):
def groupAnagrams(self, strs):
res =[]
m = Counter()
for s in strs:
s2 = ''.join(sorted(s))
if not m[s2]:m[s2]=[]
m[s2].append(s)
for k,val in m.items():res.append(val)
return res
궁금한점 혹은 모르는점 어떤 질문이든 댓글은 언제나 환영입니다.
'LeetCode' 카테고리의 다른 글
[LeetCode] 85. Maximal Rectangle (1) | 2023.10.15 |
---|---|
[LeetCode] 315. Count of Smaller Numbers After Self (2) | 2023.10.15 |
[LeetCode] 282. Expression Add Operators (0) | 2023.10.14 |
[LeetCode] 329. Longest Increasing Path in a Matrix (1) | 2023.10.14 |
[LeetCode] 875. Koko Eating Bananas (0) | 2023.09.12 |