计数字符串中冗余字符的数量 - JavaScript


我们需要编写一个 JavaScript 函数,该函数接收一个字符串,并返回字符串中冗余字符的数量。

例如 − 如果字符串是 −

const str = 'abcde'

那么输出应该是 0

如果字符串是 −

const str = 'aaacbfsc';

那么输出应该是 3

示例

以下是代码 −

const str = 'aaacbfsc';
const countRedundant = str => {
   let count = 0;
   for(let i = 0; i < str.length; i++){
      if(i === str.lastIndexOf(str[i])){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countRedundant(str));

输出

以下是控制台中的输出 −

3

更新于: 18-Sep-2020

224 次浏览

开启你的职业生涯

完成课程取得认证

开始
广告
© . All rights reserved.