GitHubSeob

C++ / 프로그래머스 / 1회 모의고사 - 외톨이 알파벳 본문

Programmers/기타

C++ / 프로그래머스 / 1회 모의고사 - 외톨이 알파벳

GitHubSeob 2024. 3. 19.
문제

 

https://school.programmers.co.kr/learn/courses/20847/lessons/255900

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제풀이

 

어떤 알파벳이 연속으로 나오는 부분이 두 부분 이상이라면 외톨이 알파벳이다.

한 칸 앞의 알파벳과 현재 알파벳을 비교하면서 같은 알파벳일 경우 다음 알파벳으로 넘어간다.

cnt라는 int형 벡터를 선언해서 알파벳이 묶여서 몇 번 등장했는지 카운트한다.

 

반복문이 종료되면 cnt벡터를 탐색하면서 2번 이상 카운트됐다면 answer에 해당 알파벳을 더해준다.

 

코드

 

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

string solution(string input_string) {
    string answer = "";
    vector<int>cnt(26, 0);
    int alp_idx(input_string[0] - 'a');
    cnt[alp_idx] = 1;
    for (int idx = 1; idx < input_string.size(); ++idx) {
        alp_idx = input_string[idx] - 'a';
        if (input_string[idx - 1] == input_string[idx]) continue;
        else ++cnt[alp_idx];
    }

    for (int idx = 0; idx < 26; ++idx) if (cnt[idx] > 1) answer += idx + 'a';
    if (answer.empty()) answer = "N";
    return answer;
}