Post

[BaekJoon] #1919 - 애너그램 만들기 [Java][C++][Python]

[BaekJoon] #1919 - 애너그램 만들기 [Java][C++][Python]

문제 링크


1. 아이디어

두 단어가 애너그램이 되려면 문자마다 나온 횟수가 같아야 하므로, 문자마다 두 단어의 횟수 차이만큼은 반드시 지워야 하고 그만큼만 지우면 횟수가 같아진다. 따라서 답은 알파벳 26종에 대해 두 단어의 횟수 차이의 절댓값을 모두 더한 값이다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int[] cnt = new int[26];
        for (char c : br.readLine().toCharArray()) {
            cnt[c - 'a']++;
        }
        for (char c : br.readLine().toCharArray()) {
            cnt[c - 'a']--;
        }

        int ans = 0;
        for (int x : cnt) {
            ans += Math.abs(x);
        }

        System.out.println(ans);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;

int cnt[26];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string s1, s2;
    cin >> s1 >> s2;

    for (char c : s1) cnt[c - 'a']++;
    for (char c : s2) cnt[c - 'a']--;

    int ans = 0;
    for (int x : cnt) {
        ans += abs(x);
    }

    cout << ans;
}
1
2
3
4
5
6
7
8
import sys
from collections import Counter

input = sys.stdin.readline

a = Counter(input().rstrip())
b = Counter(input().rstrip())
print(sum(((a - b) + (b - a)).values()))

Counter의 뺄셈은 개수가 양수인 항만 남기므로 a - b와 b - a를 더해 문자별 개수 차이의 절댓값을 구했다.


This post is licensed under CC BY 4.0 by the author.