Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การบีบอัดสตริงใน JavaScript

เราต้องเขียนฟังก์ชัน 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