計數字符串中冗餘字元的數量 - 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
廣告