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

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/8 17:48:17

我们需要编写一个 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

相关文章


有用资源