자료구조 & 알고리즘/프로그래머스
Level 1. 문자열 내 p와 y의 개수
diesuki4
2023. 2. 9. 06:55
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;
}