문제 링크
[level 1] 문자열 내 p와 y의 개수 - 12916
Note
간단한 문제, 변수를 1개만 사용(count)하고 각 조건문에서 count를 더하고 빼서 비교하는 방법도 있다.
Key
- string.charAt()
- string.toLowerCase()
- string.toUpperCase()
제출한 코드
class Solution {
boolean solution(String s) {
boolean answer = true;
//s 모두 소문자화
//p, y 갯수 세기
//비교하기
//1. s 모두 소문자
s = s.toLowerCase();
//2. s에서 p, y 개수 세기
int countP = 0 , countY = 0;
for(int i = 0 ; i < s.length() ; i++){
if(s.charAt(i) == 'p') countP++;
if(s.charAt(i) == 'y') countY++;
}
//3. 둘의 값이 다르면 false
if(countP != countY) answer = false;
//3-1. 초기값이 이미 0, answer는 true라 생략 가능
if(countP + countY == 0) answer = true;
return answer;
}
}
반응형
'Java > 알고리즘' 카테고리의 다른 글
프로그래머스/자바 lv.1 나누어 떨어지는 숫자 배열 - Arrays.sort(); (0) | 2024.03.11 |
---|---|
[Java] 프로그래머스 lv.1 약수의 합 - 루프 절반만 돌리기 (4) | 2024.03.06 |
프로그래머스/자바 lv.1 자연수 뒤집어 배열로 만들기 (0) | 2024.03.06 |