题目:
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.
检查一个字符串是否有相同数量的“x'和'o'。该方法必须返回一个布尔值,并且是大小写不敏感的。字符串可以包含任何字符。
Examples input/output:
XO("ooxx") => trueXO("xooxx") => falseXO("ooxXm") => trueXO("zpzpzpp") => true // when no 'x' and 'o' is present should return trueXO("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);
答案:
// 1function XO(str) { let x = str.match(/x/gi); let o = str.match(/o/gi); return (x && x.length) === (o && o.length);} // 2const 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;}// 分隔符位于字符串首,分割后的数组第一个元素为空// 5function 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;}