반응형

두 개의 문자열이 주어졌을 때 문자열의 순서를 재배치해서
두 문자열이 같아질 수 있는 지 확인하는 문제이다
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int a;
string i,j;
cin >> a;
for(int tmp=0; tmp<a; tmp++)
{
cin >> i >> j;
sort(i.begin(), i.end());
sort(j.begin(), j.end());
if (i==j) cout << "Possible" << "\n";
else cout << "Impossible" << "\n";
}
return 0;
}
두 문자열을 정렬만 해주고
같은지 비교만 하면 되는 간단한 로직으로 해결했다
// Authored by : OceanShape
// Co-authored by : BaaaaaaaaaaarkingDog
// http://boj.kr/a3d03c0124b544759d306668e55bbf4b
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
while (N--) {
int a[26] = {}; // 각 문자의 개수를 저장하는 배열
string s1, s2;
cin >> s1 >> s2;
for (auto c : s1) a[c-'a']++; // 첫 번째 문자열의 각 문자는 개수+1
for (auto c : s2) a[c-'a']--; // 두 번째 문자열의 각 문자는 개수-1
// 0이 아닌 배열의 요소가 있을 경우, 개수가 다른 문자가 존재하므로 false
bool isPossible = true;
// 중괄호가 없어도 문제는 없으나 가독성을 위해 삽입
for (int i : a){
if (i != 0) isPossible = false;
}
if(isPossible) cout << "Possible\n";
else cout << "Impossible\n";
}
}
찾아보니 다른 풀이들 중 창의적인게 있어 소개해보려한다
첫번째 문자열은 1씩 더해주고
두번째 문자열은 1씩 빼줘서
원소 값이 0이 아니면 개수가 다른 문자가 존재해
strfry가 아니게 되는 점을 이용한 풀이다
bool 타입 변수를 선언해서
배열을 순회하면서 true,false를 판정하는 구조가 아주 인상깊었다
반응형
'algorithm > 배열' 카테고리의 다른 글
| [algorithm] 백준 1919번 애너그램 만들기 (0) | 2026.01.10 |
|---|---|
| [algorithm] 백준 13300번 방 배정 (0) | 2026.01.10 |
| [algorithm] 백준 1475번 방 번호 (0) | 2026.01.10 |
| [algorithm] 백준 10807번 개수 세기 (0) | 2026.01.10 |
| [algorithm] 백준 2577번 숫자의 개수 (0) | 2026.01.10 |
