Make Unreal REAL.
article thumbnail
Level 1. 문자열 내 p와 y의 개수

 

 

count_if() 함수를 활용하면 쉽게 해결할 수 있다.

 

#include <iostream>
#include <cctype>
#include <algorithm>

using namespace std;

bool solution(string s)
{
    return count_if(s.begin(), s.end(), [](const char c) { return tolower(c) == 'p'; })
            == count_if(s.begin(), s.end(), [](const char c) { return tolower(c) == 'y'; });
}

 

직접 구현하면 2번을 따로 순회할 필요 없이 1번만 순회해도 된다.

 

#include <iostream>
#include <cctype>

using namespace std;

bool solution(string s)
{
    int countP = 0, countY = 0;

    for (const char c : s)
    {
        char lowerC = tolower(c);

        countP += (lowerC == 'p');
        countY += (lowerC == 'y');
    }

    return (countP == countY);
}

 

2개의 count 변수를 사용하지 않고 'P'를 발견했을 때는 더하고, 'Y'를 발견했을 때는 빼서 합이 0인지 확인해도 된다.

 

#include <iostream>
#include <cctype>

using namespace std;

bool solution(string s)
{
    int isDifferent = 0;

    for (const char c : s)
    {
        char lowerC = tolower(c);

        isDifferent += (lowerC == 'p');
        isDifferent -= (lowerC == 'y');
    }

    return !isDifferent;
}
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그