ฟังก์ชันนับจำนวนตัวอักษรที่ซ้ำ (redundant characters) ในสตริง นับเฉพาะตัวที่ปรากฏมากกว่า 1 ครั้ง
ตัวอย่าง
'abcde' → 0 (ไม่มีซ้ำ) 'aaacbfsc' → 3 (a ซ้ำ 2 ครั้ง, c ซ้ำ 1 ครั้ง = 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));
การทำงาน
lastIndexOf()หาตำแหน่งสุดท้ายของตัวอักษร- ถ้า
i !== lastIndexOfแสดงว่ายังมีตัวเดียวกันอยู่ข้างหลัง → นับว่า redundant
ผลลัพธ์
3
Complexity: O(n²) เนื่องจาก lastIndexOf เป็น O(n) ภายในลูป O(n) สำหรับสตริงยาวควรใช้ Map/Set