[ Java Level 1 ] ๋ฌธ์์ด ๋ด p์ y์ ๊ฐ์
https://programmers.co.kr/learn/courses/30/lessons/12916
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ๋ฌธ์์ด ๋ด p์ y์ ๊ฐ์ | ํ๋ก๊ทธ๋๋จธ์ค
๋๋ฌธ์์ ์๋ฌธ์๊ฐ ์์ฌ์๋ ๋ฌธ์์ด s๊ฐ ์ฃผ์ด์ง๋๋ค. s์ 'p'์ ๊ฐ์์ 'y'์ ๊ฐ์๋ฅผ ๋น๊ตํด ๊ฐ์ผ๋ฉด True, ๋ค๋ฅด๋ฉด False๋ฅผ return ํ๋ solution๋ฅผ ์์ฑํ์ธ์. 'p', 'y' ๋ชจ๋ ํ๋๋ ์๋ ๊ฒฝ์ฐ๋ ํญ์ True๋ฅผ ๋ฆฌํดํฉ๋๋ค. ๋จ, ๊ฐ์๋ฅผ ๋น๊ตํ ๋ ๋๋ฌธ์์ ์๋ฌธ์๋ ๊ตฌ๋ณํ์ง ์์ต๋๋ค. ์๋ฅผ ๋ค์ด s๊ฐ pPoooyY๋ฉด true๋ฅผ returnํ๊ณ Pyy๋ผ๋ฉด false๋ฅผ returnํฉ๋๋ค. ์ ํ์ฌํญ ๋ฌธ์์ด s์ ๊ธธ์ด : 50 ์ดํ์
programmers.co.kr
1. ์ฒ์์ผ๋ก ํผ ํ์ด
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Solution {
boolean solution(String s) {
boolean answer = true;
int a=0,b=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='p'||s.charAt(i)=='P')
++a;
else if(s.charAt(i)=='y'||s.charAt(i)=='Y')
++b;
answer = a==b? true:false;
|
cs |
์๊ฐ๊ณผ์
-๋ฐ์์จ String s๋ฅผ for๋ฌธ์ ๋๋ ค charAt()์ผ๋ก ํ๋ํ๋ ์ด๋ค ๋ฌธ์์ธ์ง ๋ด์ผ๊ฒ ๋ค.
-charAt()์ผ๋ก 'P' ๋๋ 'p'์ผ ๋ ๋ณ์ a๋ฅผ ํ๋ ์ฆ๊ฐ ์์ผ์ผ๊ฒ ๋ค
-charAt()์ผ๋ก 'Y' ๋๋ 'y'์ผ ๋ ๋ณ์ b๋ฅผ ํ๋ ์ฆ๊ฐ ์์ผ์ผ๊ฒ ๋ค.
-๊ทธ๋ฌ๋ฏ๋ก a ์ b๊ฐ ๊ฐ์ผ๋ฉด y ์ p์ ๊ฐฏ์๊ฐ ๊ฐ์ ๊ฒ ์ด๋ค.
-๋ง์ง๋ง์ผ๋ก ์ผํญ ์ฐ์ฐ์๋ก a==b๊ฐ ์ฐธ์ผ ๋ true๋ฅผ ๋ฐํ ๊ฑฐ์ง ์ผ ๋ false๋ฅผ ๋ฐํ.
2. ๋ค๋ฅธ์ฌ๋์ด ํผ ํ์ด๋ฅผ ๋ณด๊ณ ๋ค์ ํผ ํ์ด (๋ณ์ 1๊ฐ๋ง ์ฌ์ฉ)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class Solution {
boolean solution(String s) {
boolean answer = true;
int count=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='p'||s.charAt(i)=='P')
count++;
else if(s.charAt(i)=='y'||s.charAt(i)=='Y')
count--;
answer = count==0? true:false;
}
return answer;
}
}
|
cs |
์๊ฐ๊ณผ์
- ์์ ํ์ด์ ๋์ผํ๋ฐ ์ด๊ฑด ๋ณ์๋ฅผ ํ๋ ์ฌ์ฉํ๋ค.
-count๋ฅผ ์ด์ฉํด์ p ์ผ๋๋ +1 , y ์ผ ๋๋ -1
-๋ง์ง๋ง์ผ๋ก count๊ฐ 0์ด๋ฉด p์ y ์ ๊ฐ์๊ฐ ๊ฐ์ ๊ฒ์ด๋ฏ๋ก true๋ฅผ ๋ฐํํ๋ค.
3. ๋๋ค์์ผ๋ก ํ๊ธฐ
1
2
3
4
5
6
7
8
9
|
class Solution {
boolean solution(String s) {
s = s.toUpperCase();
return s.chars().filter( e -> 'P'== e).count() == s.chars().filter( e -> 'Y'== e).count();
}
}
|
cs |
-์์ง ๋๋ค์์ผ๋ก ํ์ค ๋ชจ๋ฅด๋๊น ๋์ค์ ํ์ด๋ณด์