[프로그래머스] 문자열 나누기 - c++

삼식이·2025년 6월 30일

알고리즘

목록 보기
65/84

문자열 나누기

이 문제는 문자열의 첫 문자를 x라고 할때 x와 그 외 문자들의 출현횟수가 같아지는 시점마다 answer에 1을 더해줘야 한다.

따라서 각 문자에 대해 x와 같은 문자열, x와 같지않은 문자열로 구분한다.

이때, x와 같지 않은 문자열에 대해서는 모두 같은 key값에 value 수를 증가시켜야 한다.

문제의 조건에서 s는 영어 소문자로만 이루어져 있다고 나와있으므로 x가 아닌 문자의 출현횟수는 mp['A']에 임의로 저장했다.

x문자의 출현횟수와 다른 문자의 출현횟수가 같지 않은 채로 모든 범위 탐색이 끝난 경우도 고려해 answer +=1 을 해줘야 한다.

[주석 없는 코드]

#include <string>
#include <vector>
#include <iostream>
#include <map>

using namespace std;

int solution(string s) {
    int answer = 0;
    map<char, int> mp;
    int tmp = -1;
    char c = s[0];
    for(int i=0; i<s.size(); i++) {
        if (s[i] == c) {
            mp[c]++;
            tmp = mp[c];
        } else {
            mp['A']++;
        }

        
        if (s[i] != c && mp['A'] == tmp) {
            answer++;
            mp[c] = mp['A'] = 0;
            c = s[i+1];
        }
    }
    if (mp[c] > 0 || mp['A'] >0) answer++;
    return answer;
}

[디버깅 주석 있는 코드]

#include <string>
#include <vector>
#include <iostream>
#include <map>

using namespace std;

int solution(string s) {
    int answer = 0;
    map<char, int> mp;
    int tmp = -1;
    char c = s[0];
    for(int i=0; i<s.size(); i++) {
        // cout << i << "번째 인덱스 실행 ~~ \n";
        if (s[i] == c) {
            mp[c]++;
            tmp = mp[c];
        } else {
            mp['A']++;
        }
        
        // cout << "s[i] : " << s[i] << " tmp : " << tmp << " c : " << c <<  "\n";
        
        if (s[i] != c && mp['A'] == tmp) {
            answer++;
            // cout << "-----" << c << s[i] << "-----";
            mp[c] = mp['A'] = 0;
            c = s[i+1];
            // cout << i+1 << " 번째로 이동 " << c << "가 이젠 첫문자!\n";
        }
    }
    if (mp[c] > 0 || mp['A'] >0) answer++;
    return answer;
}

0개의 댓글