백준 11328 strfry

JunSeok·2023년 1월 3일
0

백준

목록 보기
1/40

내 풀이

각 문자 개수를 저장할 배열을 두 개 만들고
26번 순회를 돌면서 배열 요소가 다르면 impossible하게 했다.

#include <bits/stdc++.h>
using namespace std;

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

    for(int i = 0; i < N; i++) {
        string a, b;
        bool fact = true;
        int a_arr[26] = {};
        int b_arr[26] = {};
        cin >> a >> b;
        if(a.length() == b.length()) {
            for(int i = 0; i < a.length(); i++) {
                a_arr[a[i]-97]++;
                b_arr[b[i]-97]++;
            }
            for(int i = 0; i < 26; i++) {
                if(a_arr[i] != b_arr[i]) fact = false;
            }
            if(fact) cout << "Possible \n";
            else cout << "Impossible \n";
        } else cout << "Impossible \n";
    }
}

더 심플한 풀이

배열을 하나만 만들어서
더하고 빼고를 함으로써 0이 나오면 두 문자가 같다고 구현했다.
더 간단한 풀이이다.

배열 순회도 더 간단한 방법을 썼다.
그리고 헷갈리지 않게 더 직관적으로 97을 빼는 것이 아닌 'a'를 빼준다.

#include <bits/stdc++.h>
using namespace std;

int main(void) {
    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']++;
        for(auto c : s2) a[c-'a']--;
        bool isPossible = true;
        for(int i : a) {
            if(i != 0) isPossible = false;
        }
        if(isPossible) cout << "Possible \n";
        else cout << "Impossible \n";
    }
}
profile
최선을 다한다는 것은 할 수 있는 한 가장 핵심을 향한다는 것

0개의 댓글