2020년/코테

[파이썬 알고리즘 인터뷰] 그룹 애너그램

위지원 2020. 12. 19. 11:07

github.com/onlybooks/algorithm-interview

배고푸당 이거하고 밥먹어야지~


 

49. 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, typically using all the original letters exactly once.

 

Example 1

Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

 

Example 2

Input: strs = [""] Output: [[""]]

 

Example 3

Input: strs = ["a"] Output: [["a"]]


 

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

from collections import defaultdict
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        res = defaultdict(list)
        for s in strs:
            res[''.join(sorted(s))].append(s)
        return res.values()

 

 

1919번: 애너그램 만들기

두 영어 단어가 철자의 순서를 뒤바꾸어 같아질 수 있을 때, 그러한 두 단어를 서로 애너그램 관계에 있다고 한다. 예를 들면 occurs 라는 영어 단어와 succor 는 서로 애너그램 관계에 있는데, occurs

www.acmicpc.net

 

str_1 = input()
str_2 = input()

from collections import Counter
if sorted(str_1) != sorted(str_2):
    counter_str_1 = Counter(str_1)
    counter_str_2 = Counter(str_2)
    print(sum((counter_str_1-counter_str_2).values())
    +sum((counter_str_2-counter_str_1).values()))
        
else:
    print(0)