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;
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 1. 삼총사 (0) | 2023.02.11 |
---|---|
Level 1. 같은 숫자는 싫어 (0) | 2023.02.10 |
Level 0. 유한소수 판별하기 (0) | 2023.02.08 |
Level 0. 소인수분해 (0) | 2023.02.07 |
Level 0. 구슬을 나누는 경우의 수 (0) | 2023.02.06 |