เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและเริ่มจับคู่อักขระจาก 0 และทุกครั้งที่ฟังก์ชันพบอักขระที่ไม่ซ้ำกัน (ไม่ซ้ำกัน) ควรเพิ่มจำนวนการแมปขึ้น 1 มิฉะนั้นจะจับคู่ตัวเลขเดียวกันสำหรับ อักขระที่ซ้ำกัน
ตัวอย่างเช่น − หากสตริงคือ −
const str = 'heeeyyyy';
จากนั้นผลลัพธ์ควรเป็น −
const output = [0, 1, 1, 1, 2, 2, 2, 2];
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'heeeyyyy';
const mapString = str => {
const res = [];
let curr = '', count = -1;
for(let i = 0; i < str.length; i++){
if(str[i] === curr){
res.push(count);
}else{
count++;
res.push(count);
curr = str[i];
};
};
return res;
};
console.log(mapString(str)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
[ 0, 1, 1, 1, 2, 2, 2, 2 ]