프로그래머스/level 1
[프로그래머스] 문자열 내 p와 y의 개수
binaryJournalist
2021. 9. 7. 12:57
반응형
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

** Javascript
1) (오답임)
처음에 제출했던 코드인데 테스트케이스가 추가되면서 틀린 답이 되었다. p 와 y가 모두 없는 경우 때문이다.
function solution(s){
var string = s.toLowerCase();
if (!string.includes("p")) return false;
if (!string.includes("y")) return false;
return (string.match(/p/g) || []).length === (string.match(/y/g) || []).length;
}
2)
조건문만 삭제해주면 된다.
function solution(s){
var string = s.toLowerCase();
return (string.match(/p/g) || []).length === (string.match(/y/g) || []).length;
}
** Java
1)
import java.util.*;
class Solution {
boolean solution(String s) {
String[] strings = s.toLowerCase().split("");
int p = 0;
int y = 0;
for (String str : strings) {
if (str.equals("p")) p++;
if (str.equals("y")) y++;
}
return Objects.equals(p, y);
}
}
2)
import java.util.*;
class Solution {
boolean solution(String s) {
String[] strings = s.toLowerCase().split("");
int cnt = 0;
for (String str : strings) {
if (str.equals("p")) cnt++;
if (str.equals("y")) cnt--;
}
return Objects.equals(cnt, 0);
}
}
** Python
1)
def solution(s) :
cnt = 0
for i in s.lower() :
if i == "p" :
cnt += 1
if i == "y":
cnt -= 1
return cnt == 0
2) 다른 풀이 (추천 1등)
def solution(s) :
return s.lower().count('p') == s.lower().count('y')반응형