บางครั้งคนทำซ้ำตัวอักษรเพื่อแสดงความรู้สึกเพิ่มเติม เช่น "hello" -> "heeellooo", "hi" -> "hiiii" ในสตริงแบบ "heeellooo" เรามีกลุ่มตัวอักษรที่ติดกันและเหมือนกันทั้งหมด: "h", "eee", "ll", "ooo"
สำหรับสตริง S ที่กำหนด คำค้นหาจะเป็น stretchy หากสามารถทำให้เท่ากับ S ได้โดยการประยุกต์ใช้การขยายกลุ่มหลายครั้ง: เลือกกลุ่มที่ประกอบด้วยตัวอักษร c และเพิ่มตัวอักษร c เข้าไปในกลุ่มจนขนาดกลุ่มเป็น 3 หรือมากกว่า
ตัวอย่างเช่น เริ่มจาก "hello" เราสามารถขยายกลุ่ม "o" ได้เป็น "hellooo" แต่ไม่สามารถได้ "helloo" เพราะกลุ่ม "oo" มีขนาดน้อยกว่า 3 เรายังสามารถขยายอีก เช่น "ll" -> "lllll" ได้ "helllllooo" ถ้า S = "helllllooo" คำค้นหา "hello" จะเป็น stretchy เพราะสองการขยาย: query = "hello" -> "hellooo" -> "helllllooo" = S
โดยได้รับรายการคำค้นหา เราต้องคืนจำนวนคำที่เป็น stretchy
ตัวอย่างเช่น
ถ้าสตริงอินพุทคือ
const str = 'heeellooo';
และรายการคำคือ
const words = ["hello", "hi", "helo"];
ผลลัพธ์ควรเป็น
const output = 1
ตัวอย่างโค้ด
โค้ดสำหรับการทำงานนี้จะเป็นดังนี้
const str = 'heeellooo'; const words = ["hello", "hi", "helo"];
const extraWords = (str, words) => {
let count = 0;
for (let w of words) {
let i = 0;
let j = 0;
for (; i < str.length && j < w.length && w[j] === str[i];) {
let lenS = 1;
let lenW = 1;
for (; i+lenS < str.length && str[i+lenS] === str[i]; lenS++);
for (; j+lenW < w.length && w[j+lenW] === w[j]; lenW++);
if (lenS < lenW || lenS > lenW && lenS < 3) break;
i += lenS;
j += lenW;
}
if (i === str.length && j === w.length) {
count++;
}
}
return count;
}
console.log(extraWords(str, words));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
1