기초 PS #boj 2941

0ne·2024년 1월 28일

Algorithm

목록 보기
5/22

문제

입력

첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문자와 '-', '='로만 이루어져 있다.

단어는 크로아티아 알파벳으로 이루어져 있다. 문제 설명의 표에 나와있는 알파벳은 변경된 형태로 입력된다.

출력

입력으로 주어진 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.

풀이

처음 나의 풀이

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string str;
    cin >> str;
    
    string remove[] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="}; 
    int count = 0;
    size_t pos;

    for (int i = 0; i < 8; i++) {
        while ((pos = str.find(remove[i])) != string::npos) {
            count++;
            str.erase(pos, remove[i].length());
        } 
    }

    count += str.length();
    cout << count;
}

크로아티아 문자를 발견시 제거 & 카운트 올리기 방식.
-> but, 제거 후 다시 크로아티아 문자가 생기면 의도와 다르게 동작함

수정 : 해당 이슈의 해결

치환 후 개수 세기!

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string str;
    cin >> str;
    
    string remove[] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="}; 
    size_t pos;
    
    for (int i = 0; i < 8; i++) {
        while ((pos = str.find(remove[i])) != string::npos) {
            str.replace(pos, remove[i].length(), "#");
        } 
    }
    cout << str.length();
}
profile
@Hanyang univ(seoul). CSE

0개의 댓글