HackerRank Strings: Making Anagrams

x·2021년 5월 7일
0

problem-solving

목록 보기
15/18

주어진 문자열 a, b가 anagram이 되기 위해 a, b에서 제거해야 할 문자의 총 개수 구하는 문제다
Counter 클래스를 사용해 각 문자의 개수를 구한다
a, b 모두에 존재하는 문자의 개수를 빼주고 남은 개수의 총합을 구하면 된다

#!/bin/python3

import os
from collections import Counter, defaultdict


def make_anagram(a: str, b: str) -> int:
    a_counter = Counter(a)
    b_counter = Counter(b)
    check_dict = defaultdict()

    for c in a:
        if c in b_counter:
            if c in check_dict:
                continue
            check_dict[c] = True
            if a_counter[c] >= b_counter[c]:
                a_counter[c] -= b_counter[c]
                b_counter[c] = 0
            else:
                b_counter[c] -= a_counter[c]
                a_counter[c] = 0

    for c in b:
        if c in a_counter:
            if c in check_dict:
                continue
            check_dict[c] = True
            if b_counter[c] >= a_counter[c]:
                b_counter[c] -= a_counter[c]
                a_counter[c] = 0
            else:
                a_counter[c] -= b_counter[c]
                b_counter[c] = 0

    return sum(a_counter.values()) + sum(b_counter.values())


if __name__ == "__main__":
    fptr = open(os.environ["OUTPUT_PATH"], "w")

    a = input()

    b = input()

    res = make_anagram(a, b)

    fptr.write(str(res) + "\n")

    fptr.close()

0개의 댓글