본문 바로가기
C++

[프로그래머스] 모음 제거

by 띰쥬 2025. 9. 4.
728x90
반응형
SMALL
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

bool is_vowel(unsigned char c)
{
    switch (c) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
        case 'A': case 'E': case 'I': case 'O': case 'U':
            return true;
        default: return false;
    }
}

string solution(string my_string) {
    my_string.erase(
        remove_if(my_string.begin(), my_string.end(),
                  [](unsigned char ch){ return is_vowel(ch); }),
        my_string.end()
    );
    return my_string;
}

 

포인트

  • erase–remove 관용구:
    remove_if로 “지울 후보”를 뒤로 몰고, erase로 뒷부분을 잘라내 최종 삭제합니다.
  • 람다 파라미터와 is_vowel의 매개변수를 unsigned char 로 맞춰둔 건 좋은 습관입니다. (문자 자료형의 부호 문제 예방)
  • 대문자 모음도 함께 처리합니다.

C++20 한 줄 버전 (std::erase_if)

컴파일러가 C++20을 지원한다면 더 간결하게 쓸 수 있어요.

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

constexpr bool is_vowel(unsigned char c)
{
    switch (c) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
        case 'A': case 'E': case 'I': case 'O': case 'U': return true;
        default: return false;
    }
}

string solution(string s) {
    std::erase_if(s, [](unsigned char ch){ return is_vowel(ch); });
    return s;
}
728x90
반응형
LIST

댓글