4. Exes and Ohs

187 阅读1分钟

Check to see if a string has the same amount of x's and o's. The method must return a boolean and be case insensitive. The string can contain any char.

Example:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
我的解法
function XO(str) {
   if (!str) {
     return false;
   }
   var oArr = [],
       xArr = [],
       arr = str.split('')
   arr.forEach((item) => {
      item = item.toLowerCase()
      if (item == 'o') {
         oArr.push(item)
      }
      if (item == 'x') {
         xArr.push(item)
      }
    })
    return oArr.length == xArr.length
 }
【unlock solutions】中摘取的各种解法:

解法1:(match匹配,match没有匹配结果返回的是null,所以用了||处理):
function XO(str) {
    return (str.match(/o/gi) || []).length == (str.match(/x/gi) || []).length;
}

解法2:(replace过滤不符合要求的字符)
function XO(str) {
    return str.replace(/o/gi, '').length == str.replace(/x/gi, '').length;
}

解法3:(计算,最后比较值)
function XO(str) {
    var sum = 0;
    for (var i = 0; i < str.length; i++) {
      if (str[i].toLowerCase() == 'x') sum++;
      if (str[i].toLowerCase() == 'o') sum--;
   }
   return sum == 0;
}