const count = ({ countOfP, countOfY }, current) => {
if (current == "p") {
countOfP++;
} else if (current == "y") {
countOfY++;
}
return { countOfP, countOfY };
};
const solution = (s) => {
const { countOfP, countOfY } = s
.toLowerCase()
.split("")
.reduce(count, { countOfP: 0, countOfY: 0 });
if (countOfP == countOfY) {
return true;
}
return false;
};
reduce 생각보다 좋네...
toLowerCase메소드가 단순히 문자 하나하나가 아니라 문자열에도 적용할 수 있다는 게 왜 이렇게 어색한지 모르겠다.
그리고 다른 사람의 풀이를 보니 split메소드를 좀 더 유용하게 사용하는 방법이 있었다
(나는 모든 문제를 풀 때 순회 처리를 당연하게 생각하고 있는데, 대체 어떻게 이런 발상을 하는 걸까...)
function solution(s) {
s = s.toLowerCase().split("");
const countOfP = s.filter((char) => char == "p").length;
const countOfY = s.filter((char) => char == "y").length;
return countOfP == countOfY ? true : false;
}