본문 바로가기
Programming/Baekjoon Online Judge

[BOJ 백준] 1919번 : 애너그램 만들기(C)

by 장경혁tv 2025. 6. 23.

목차

1. 문제

2. 풀이

3. 메시지

1. 문제

https://www.acmicpc.net/problem/1919

2. 풀이

언어 : C

애너그램 관계, 즉 두 단어가 철자의 순서를 바꾸어 서로 같아지기 위해 제거해야 할 문자의 개수를 구해야 한다.

두 문자열을 입력받아 각각 알파벳의 개수를 구한다.

그리고 마지막에 두 알파벳이 모두 0 이상이면 두 단어 사이에서 애너그램 관계가 될 수 있으므로, 두 알파벳에서 하나씩 감소시킨다.

그러면서 제거해야 할 문자의 수를 두 알파벳의 개수의 합(둘 중 하나는 0)을 더한다.

소스코드

https://github.com/NewLandTV/Baekjoon-Online-Judge/blob/main/C/1919.c

 

Baekjoon-Online-Judge/C/1919.c at main · NewLandTV/Baekjoon-Online-Judge

This repository is where problems solved on the Baekjoon Online Judge site are uploaded. - NewLandTV/Baekjoon-Online-Judge

github.com

 

#include <stdio.h>
#include <string.h>

int main(void)
{
	int i;
	char s1[1001];
	char s2[1001];
	int alphabet1[26] = { 0, };
	int alphabet2[26] = { 0, };
	int count = 0;
	
	scanf("%s", s1);
	
	for (i = 0; i < strlen(s1); i++)
	{
		alphabet1[s1[i] - 'a']++;
	}
	
	scanf("%s", s2);
	
	for (i = 0; i < strlen(s2); i++)
	{
		alphabet2[s2[i] - 'a']++;
	}
	
	for (i = 0; i < 26; i++)
	{
		while (alphabet1[i] > 0 && alphabet2[i] > 0)
		{
			alphabet1[i]--;
			alphabet2[i]--;
		}
		
		count += alphabet1[i] + alphabet2[i];
	}
	
	printf("%d", count);
	
	return 0;
}

3. 메시지

이렇게 문자열을 다루는 것은 내가 게임을 만들 때, 많이 쓰이므로 색다르게 느껴진 자료형 중 하나였다.

또한 각 문자열에서 알파벳의 수를 구하고, 이를 활용한 문제의 접근이 생각보다 쉬웠다.

댓글