ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง ฟังก์ชันควรคืนค่าอาร์เรย์ 2 สมาชิก สมาชิกแรกคือตัวอักษรที่มีการปรากฏติดต่อกันมากที่สุดในสตริง สมาชิกที่สองคือจำนวนครั้งที่ปรากฏ
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const str = 'tdfdffddffsdsfffffsdsdsddddd';
const findConsecutiveCount = (str = '') => {
let res = '';
let count = 1;
let arr = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i + 1]) {
count++;
} else {
if (arr.every(v => v < count)) {
res = str[i] + count;
}
arr.push(count);
count = 1;
}
}
return !res ? ['', 0] : [res.slice(0, 1), res.slice(1) * 1];
};
console.log(findConsecutiveCount(str));
ผลลัพธ์
['f', 5]
คำอธิบายเพิ่มเติม
จากสตริง หา character run ยาวสุด: 'fffff' (5 f ติดกัน) โค้ดเก็บ count ทุก run ใน arr แล้วเช็คว่า run ปัจจุบัน > ทุก run ก่อนหน้า (arr.every) ซึ่งเป็น O(n²) ควรเก็บ max แทน