xo.js (7kyu 09)

Codewars 알고리즘 풀이


Description

  • Check to see if a string has the same amount of ‘x’s and ‘o’s.
    • 문자열이 동일한 수의 ‘x’와 ‘o’를 가지고 있는지 확인한다.
  • The method must return a boolean and be case insensitive.
    • boolean 값을 반환한다.
    • 대소문자를 구분하지 않는다.
  • The string can contain any char.
    • 문자열은 모든 글자를 포함할 수 있다.



Solution 01

function xo(str) {
  let countX = 0;
  let countO = 0;
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] === 'x' || str[i] === 'X') countX++;
    if (str[i] === 'o' || str[i] === 'O') countO++;
  }
  
  return countX === countO;
}

xo('');        // true
xo('xo');      // true
xo('OX');      // true
xo('xxOo');    // true
xo('xxxo');    // false
xo('axbo');    // true
xo('aaaxbo');  // true


Solution 02

function xo(str) {
  str = str.toLowerCase();
  let countX = 0;
  let countO = 0;
  
  for (let i = 0; i < str.length; i++) {
    if (str[i] === 'x') countX++;
    if (str[i] === 'o') countO++;
  }
  
  return countX === countO;
}

xo('');        // true
xo('xo');      // true
xo('OX');      // true
xo('xxOo');    // true
xo('xxxo');    // false
xo('axbo');    // true
xo('aaaxbo');  // true


Solution 03

function xo(str) {
  return str.toLowerCase().split('x').length === str.toLowerCase().split('o').length;
}

xo('');        // true
xo('xo');      // true
xo('OX');      // true
xo('xxOo');    // true
xo('xxxo');    // false
xo('axbo');    // true
xo('aaaxbo');  // true


Solution 04

function xo(str) {
  let a = str.replace(/x/gi, '');
  let b = str.replace(/o/gi, '');
  
  return a.length === b.length;
}

xo('');        // true
xo('xo');      // true
xo('OX');      // true
xo('xxOo');    // true
xo('xxxo');    // false
xo('axbo');    // true
xo('aaaxbo');  // true


Solution 05

function xo(str) {
  let x = str.match(/x/gi);
  let o = str.match(/o/gi);
  
  return (x && x.length) === (o && o.length);
}

xo('');        // true
xo('xo');      // true
xo('OX');      // true
xo('xxOo');    // true
xo('xxxo');    // false
xo('axbo');    // true
xo('aaaxbo');  // true