我们需要编写一个将字符串作为唯一参数的JavaScript函数。我们函数的任务是计算输入字符串中的所有连续子字符串,这些子字符串恰好包含一个不同的字母。
然后,该函数应返回所有此类子字符串的计数。
例如-
如果输入字符串是-
const str = 'iiiji';
那么输出应该是-
const output = 8;
因为所需的字符串是-
'iii', 'i', 'i', 'i', 'i', 'j', 'ii', 'ii'
以下是代码-
const str = 'iiiji'; const countSpecialStrings = (str = '') => { let { length } = str; let res = length; if(!length){ return length; }; for (let j = 0, i = 1; i < length; ++ i) { if (str[i] === str[j]) { res += i - j; } else { j = i; } }; return res; } console.log(countSpecialStrings(str));输出结果
以下是控制台输出-
8