일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- SseEmitter
- jQuery
- web
- python
- programmers
- oauth
- JPA
- bean
- Spring Security
- Java
- DI
- Stream
- spring
- html
- jenkins
- real time web
- 항해99
- 생명주기 콜백
- session
- Hibernate
- javascript
- hanghae99
- Project
- WIL
- server send event
- Anolog
- google oauth
- flask
- cookie
- JWT
Archives
- Today
- Total
끄적끄적 코딩일지
[Programmers]문자열 내 p와 y의 개수(난이도:★★★) 본문
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
import java.util.Arrays;
class Solution {
boolean solution(String s) {
return solutionA(s);
}
// 솔루션 A
public boolean solutionA(String s){
String tmp = toUpperCase(s);
int countP = getCount(tmp,'P');
int countY = getCount(tmp,'Y');
if(countP == 0 && countY == 0)
return true;
else
return countP == countY;
}
// 솔루션 B
// Replace 사용
// 전체 길이에서 p,y각각 replace한값을 빼면 p와 y의 개수를 알 수 있다.
public boolean solutionB(String s){
int totalLen = s.length();
String tmp = s.toUpperCase();
int countP = totalLen - tmp.replace("P","").length();
int countY = totalLen - s.toUpperCase().replace("Y","").length();
if(countP == 0 && countY == 0)
return true;
else
return countP == countY;
}
// count 구현
public int getCount(String a,char b) {
char[] arr = a.toCharArray();
int count = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] == b)
count++;
}
return count;
}
// toUpperCase 구현
public String toUpperCase(String c) {
char[] arr = c.toCharArray();
for(int i = 0; i < arr.length; i++) {
if(arr[i] >= 97 && arr[i] <= 122 ) {
arr[i] = (char) (arr[i] - 32);
}
}
return new String(arr);
}
}
'알고리즘' 카테고리의 다른 글
[Programmers]서울에서 김서방 찾기(난이도:★★★) (0) | 2022.05.16 |
---|---|
[Programmers]문자열 다루기 기본(난이도:★★★) (0) | 2022.05.16 |
[Programmers]내적(난이도:★★★) (0) | 2022.05.16 |
[Programmers]나누어 떨어지는 숫자 배열(난이도:★★★) (0) | 2022.05.16 |
[Programmers]2016년(난이도:★★★) (0) | 2022.05.16 |