본문 바로가기
👩‍💻 Programming/Coding Test 문제 풀이

[Programmers] level 1: 문자열 내 p와 y의 개수 by JavaScript

by codingBear 2022. 7. 9.
728x90
반응형

 이번 문제를 풀어 보고 싶다면? 아래 링크를 클릭하세요!

 문제 풀러 가기!


  나는 이 문제를 객체를 활용하여 풀었다. 우선 'p'와 'y'를 가려내기 위해 인자로 받은 s를 소문자로 변환하고, key 'p'와 'y'에 각각 0을 할당한 객체를 선언한다. 그런 다음 for 반복문으로 문자열 s를 탐색하면서 'p' 혹은 'y'가 등장할 경우 해당 key의 값을 1씩 증가시켜줬다. 마지막으로 key 'p' 혹은 'y'의 값이 0이거나 두 key의 값이 같은 경우 true를 나머지 경우 false를 반환하도록 했다.

 다른 사람의 풀이 중 reduce() 메서드를 활용한 풀이가 참고할 만해서 갖고 왔다. 스프레드 연산자로 문자열 s를 배열에 담고 소문자로 변환한다. 그런 다음 reduce() 메서드의 초기값에 0을 주고 현재값(cur)가 'p'일 경우 축적값(acc)에 1을 더하고, 'y'일 경우 1을 뺀다. 결괏값이 0인 경우 false이므로 삼항연산자에 대입하게 되면 결과적으로 true(두 번째 놓인 값)을 반환하고 나머지 경우에는 false를 반환한다. JavaScript에서 0이외의 값이 어째서 true로 취급되는지는 아래 함께 보기의 링크를 참고하면 되겠다.

 

Solutions

Solutions
function solution(s) {
  /* Obj Ver. */
  const pyCnts = { p: 0, y: 0 };
  s = s.toLowerCase();

  for (const c of s) {
    if (c === 'p') pyCnts['p']++;
    else if (c === 'y') pyCnts['y']++;
  }

  return (pyCnts['p'] === 0 && pyCnts['y'] === 0) || pyCnts['p'] === pyCnts['y']
    ? true
    : false;

  /* reduce() Ver. */
  return [...s.toLowerCase()].reduce((acc, cur) => {
    if (cur === 'p') return acc + 1;
    else if (cur === 'y') return acc - 1;
    return acc;
  }, 0)
    ? false
    : true;
}

함께 보기

 

Conditional (ternary) operator - JavaScript | MDN

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execu

developer.mozilla.org

 

Truthy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false, 0, -0, 0n, "", null, undefined, and NaN.

developer.mozilla.org

 

Falsy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context.

developer.mozilla.org

 

728x90
반응형

댓글