เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่อาจมีอักขระที่ซ้ำกันอย่างต่อเนื่อง
ฟังก์ชันควรบีบอัดสตริงเช่นนี้ −
'wwwaabbbb' -> 'w3a2b4' 'kkkkj' -> 'k4j'
และหากความยาวของสตริงที่บีบอัดมากกว่าหรือเท่ากับสตริงเดิม เราควรส่งคืนสตริงเดิม
ตัวอย่างเช่น −
'aab' สามารถบีบอัดเป็น 'a2b1' ได้ แต่มันเพิ่มความยาวเป็น 4 ดังนั้นฟังก์ชันของเราจะคืนค่า 'aab'
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const str1 = 'wwwaabbbb';
const str2 = 'kkkkj';
const str3 = 'aab';
const compressString = (str = '') => {
let res = '';
let count = 1;
for(let i = 0; i < str.length; i++){
let cur = str[i];
let next = str[i + 1];
if(cur === next){
count++;
}else{
res += cur + String(count);
count = 1;
};
}
return res.length < str.length ? res : str;
};
console.log(compressString(str1));
console.log(compressString(str2));
console.log(compressString(str3)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
3a2b4 k4j1 aab