題目:數組
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 contains any char.spa
檢查一個字符串是否有相同數量的「x'和'o'。該方法必須返回一個布爾值,而且是大小寫不敏感的。字符串能夠包含任何字符。code
Examples input/output:blog
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
Sample Tests:字符串
Test.assertEquals(XO('xo'),true); Test.assertEquals(XO("xxOo"),true); Test.assertEquals(XO("xxxm"),false); Test.assertEquals(XO("Oo"),false); Test.assertEquals(XO("ooom"),false);
答案:input
// 1 function XO(str) { let x = str.match(/x/gi); let o = str.match(/o/gi); return (x && x.length) === (o && o.length); } // 2 const XO = str => { str = str.toLowerCase().split(''); return str.filter(x => x === 'x').length === str.filter(x => x === 'o').length; } // 3 function XO(str) { // 字符串中的x被''替換,字符串長度改變,新字符串爲a var a = str.replace(/x/gi, ''); b = str.replace(/o/gi, ''); return a.length === b.length; } // 4 判斷在給定字符串x或o中,分隔符發生的每一個點,分割的字符串數組的長度是否相等 function XO(str) { return str.toLowerCase().split('x').length === str.toLowerCase().split('o').length; } // 分隔符位於字符串首,分割後的數組第一個元素爲空 // 5 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; }