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

การหาความยาวสตริงย่อยสระเสียงติดกันที่ยาวที่สุดใน JavaScript

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง ฟังก์ชันควรคืนค่าความยาวของสตริงย่อยติดต่อกัน (contiguous substring) ที่ยาวที่สุดที่ประกอบด้วยสระเสียงอย่างเดียว

ตัวอย่าง

โค้ดตัวอย่างด้านล่าง:

const str = 'schooeal';
const findLongestVowel = (str = '') => {
  let cur = 0;
  let max = 0;
  for (let i = 0; i < str.length; ++i) {
    if ("aeiou".includes(str[i])) {
      cur++;
      if (cur > max) {
        max = cur;
      }
    } else {
      cur = 0;
    }
  }
  return max;
};
console.log(findLongestVowel(str));

ผลลัพธ์

4

คำอธิบายเพิ่มเติม

จาก 'schooeal': s c h oo e a l → 'ooea' ยาว 4 ตัวอักษร (o,o,e,a) โค้ดใช้ sliding window นับความยาวสระติดกัน รีเซ็ตเมื่อเจอพยัญชนะ O(n) time, O(1) space