티스토리 뷰
https://programmers.co.kr/learn/courses/30/lessons/12916
코딩테스트 연습 - 문자열 내 p와 y의 개수
대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 solution를 완성하세요. 'p', 'y' 모두 하나도 없는 경우는 항상 True를
programmers.co.kr
나는 변수 두 개 , equalsIgnoreCase 사용
class Solution {
boolean solution(String s) {
boolean answer = true;
int pp = 0, yy = 0;
for(int i=0; i<s.length(); i++) {
if(s.substring(i, i+1).equalsIgnoreCase("p"))
pp++;
if(s.substring(i, i+1).equalsIgnoreCase("y"))
yy++;
}
if(pp != yy)
answer = false;
return answer;
}
}
변수 한 개 사용
class Solution {
boolean solution(String s) {
boolean answer = true;
s = s.toLowerCase();
int count = 0;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == 'p')
count++;
if(s.charAt(i) == 'y')
count--;
}
if(count == 0)
answer = true;
else
answer = false;
return answer;
}
}
'ALGORITHM' 카테고리의 다른 글
[JAVA] [프로그래머스] Level 1 - 연습문제 - 서울에서 김서방 찾기 (0) | 2020.09.01 |
---|---|
[JAVA] [프로그래머스] Level 1 - 연습문제 - 문자열 내림차순으로 배치하기 (0) | 2020.09.01 |
[JAVA] [프로그래머스] Level 1 - 연습문제 - 문자열 내 마음대로 정렬하기 (0) | 2020.09.01 |
[JAVA] [프로그래머스] Level 1 - 연습문제 - 두 정수 사이의 합 (0) | 2020.09.01 |
[JAVA] [프로그래머스] Level 1 - 연습문제 - 나누어 떨어지는 숫자 배열 (0) | 2020.08.31 |