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

สร้างคำที่ยาวที่สุดจากสตริงโดยการลบตัวอักษร (Longest Word Formed) ใน JavaScript

ปัญหา

รับสตริง str และอาร์เรย์คำ arr ลบตัวอักษรจาก str เพื่อสร้างคำใน arr ให้ยาวที่สุด

ตัวอย่าง

const str = 'sdgfdfghdjh'; 
const arr = ['sdf', 'fghj', 'gfdfg', 'absc', 'a', 'hasl'];

คำที่สร้างได้และยาวสุด: 'gfdfg' (ความยาว 5)

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

const str = 'sdgfdfghdjh'; 
const arr = ['sdf', 'fghj', 'gfdfg', 'absc', 'a', 'hasl']; 
const findLongestWord = (str = '', arr = []) => { 
  arr.sort((a, b) => { 
    if (a.length !== b.length) return b.length - a.length; 
    return a.localeCompare(b); 
  }); 
  for(const word of arr){ 
    let index = -1; 
    for(const char of word){ 
      index = str.indexOf(char, index + 1); 
      if(index < 0) break; 
    } 
    if (index >= 0) return word; 
  } 
  return ''; 
}; 
console.log(findLongestWord(str, arr));

คำอธิบาย

  • เรียง arr ตามความยาวมากไปน้อย แล้วค่าอักษร
  • ตรวจสอบแต่ละคำว่าตัวอักษรทุกตัวปรากฏใน str ตามลำดับหรือไม่
  • คำแรกที่ผ่านคือคำตอบ

ผลลัพธ์

gfdfg