๋ฌธ์์ด ๋ด p์ y์ ๊ฐ์
๋๋ฌธ์์ ์๋ฌธ์๊ฐ ์์ฌ์๋ ๋ฌธ์์ด s๊ฐ ์ฃผ์ด์ง๋๋ค. s์ 'p'์ ๊ฐ์์ 'y'์ ๊ฐ์๋ฅผ ๋น๊ตํด ๊ฐ์ผ๋ฉด True, ๋ค๋ฅด๋ฉด False๋ฅผ return ํ๋ solution๋ฅผ ์์ฑํ์ธ์. 'p', 'y' ๋ชจ๋ ํ๋๋ ์๋ ๊ฒฝ์ฐ๋ ํญ์ True๋ฅผ ๋ฆฌํดํฉ๋๋ค. ๋จ, ๊ฐ์๋ฅผ ๋น๊ตํ ๋ ๋๋ฌธ์์ ์๋ฌธ์๋ ๊ตฌ๋ณํ์ง ์์ต๋๋ค.
์๋ฅผ ๋ค์ด s๊ฐ "pPoooyY"๋ฉด true๋ฅผ returnํ๊ณ "Pyy"๋ผ๋ฉด false๋ฅผ returnํฉ๋๋ค.
์ ํ ์กฐ๊ฑด
- ๋ฌธ์์ด s์ ๊ธธ์ด : 50 ์ดํ์ ์์ฐ์
- ๋ฌธ์์ด s๋ ์ํ๋ฒณ์ผ๋ก๋ง ์ด๋ฃจ์ด์ ธ ์์ต๋๋ค.
์ ์ถ๋ ฅ ์
s | answer |
---|---|
"pPoooyY" | true |
"Pyy" | false |
- ์
์ถ๋ ฅ ์ #1
'p'์ ๊ฐ์ 2๊ฐ, 'y'์ ๊ฐ์ 2๊ฐ๋ก ๊ฐ์ผ๋ฏ๋ก true๋ฅผ return ํฉ๋๋ค.
- ์
์ถ๋ ฅ ์ #2
'p'์ ๊ฐ์ 1๊ฐ, 'y'์ ๊ฐ์ 2๊ฐ๋ก ๋ค๋ฅด๋ฏ๋ก false๋ฅผ return ํฉ๋๋ค.
๋ฌธ์ ํ์ด
s ๋ฌธ์์ด์ p ๋๋ P๊ฐ ํฌํจ๋๋ฉด cnt ๊ฐ์ ๊น๊ณ , y ๋๋ Y๊ฐ ํฌํจ๋๋ฉด ๋ํด์ฃผ๋ ์์ผ๋ก
"pPoooyY"๊ฐ ๋ค์ด๊ฐ ์์ ๊ฒฝ์ฐ์๋ cnt ๊ฐ์ด +2๊ฐ ๋์๋ค๊ฐ -1๋ก ์ค์ด๋ค์ด ๊ฒฐ๊ณผ๊ฐ์ด 1, ์ฆ true๊ฐ ๋๋ค.
๋ฐ๋์ ๊ฒฝ์ฐ๋ -1์ด ๋๊ธฐ ๋๋ฌธ์ false๊ฐ ๋๋ค.
๊ฒฐ๊ณผ์ ์ผ๋ก "pPoooyY"๋ฉด true๋ฅผ returnํ๊ณ "Pyy"๋ผ๋ฉด false๋ฅผ returnํ๊ฒ ๋๋ค.
#include <string>
#include <iostream>
using namespace std;
bool solution(string s)
{
bool answer = true;
int cnt = 0;
for(int i=0; i<s.length(); i++)
if(s[i] == 'p' || s[i] == 'P') cnt++;
else if(s[i] == 'y' || s[i] == 'Y') cnt--;
return cnt ? false : true;
return answer;
}
๋ค๋ฅธ ํ์ด ๋ฐฉ์
์ถ์ฒ : ํ๋ก๊ทธ๋๋จธ์ค ์ค์ฟจ
p, P๊ฐ ํฌํจ๋๋ฉด int p๊ฐ์ ์ฆ๊ฐ์ํค๊ณ , y, Y๊ฐ ํฌํจ๋๋ฉด int y๊ฐ์ ์ฆ๊ฐ์์ผ ๊ฒฐ๊ณผ์ ์ผ๋ก p์ y๊ฐ ๊ฐ์ ๊ฐ์ผ ๋์ true๋ฅผ ๋ฐํ์ํจ๋ค.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
bool solution(string s)
{
int p = 0;
int y = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'p' || s[i] == 'P')
p++;
else if (s[i] == 'y' || s[i] == 'Y')
y++;
}
return p == y;
}
๋๊ธ