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

หาคำที่ยาวที่สุดในสตริงด้วย JavaScript

โจทย์

รับสตริงเข้ามา หา คำ (Word) ที่มีความยาวมากที่สุด คืนค่าคำนั้น

ตัวอย่าง

const str = 'Coding in JavaScript is really fun';
// Output: 'JavaScript' (10 ตัวอักษร)

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

const str = 'Coding in JavaScript is really fun';

const findLongest = (str = '') => {
  const strArr = str.split(' ');
  const word = strArr.reduce((acc, val) => {
    let { length: len } = acc;
    if (val.length > len) {
      acc = val;
    }
    return acc;
  }, '');
  return word;
};

console.log(findLongest(str));

ผลลัพธ์

JavaScript

วิธีทันสมัย (ES6+)

1. ใช้ sort (สั้นที่สุด)

const findLongestSort = (str) => 
  str.split(' ').sort((a, b) => b.length - a.length)[0];

2. ใช้ reduce (ไม่ต้อง sort ทั้งอาร์เรย์)

const findLongestReduce = (str) => 
  str.split(' ').reduce((longest, word) => 
    word.length > longest.length ? word : longest, '');

3. ใช้ for...of (เร็วที่สุด)

const findLongestLoop = (str) => {
  let longest = '';
  for (const word of str.split(' ')) {
    if (word.length > longest.length) longest = word;
  }
  return longest;
};

กรณีพิเศษและ Edge Cases

const findLongestRobust = (str) => {
  if (!str || !str.trim()) return '';
  
  // จัดการ punctuation: ตัดเครื่องหมายวรรคตอนออก
  const words = str.match(/\b\w+\b/g) || [];
  
  return words.reduce((longest, word) => 
    word.length > longest.length ? word : longest, '');
};

// ทดสอบ
console.log(findLongestRobust('Hello, world!!!')); // 'Hello' (5) ไม่ใช 'world!!!' (7)
console.log(findLongestRobust('')); // ''
console.log(findLongestRobust('a bb ccc')); // 'ccc'

หาคำที่ยาวที่สุด N อันดับแรก

const findLongestN = (str, n = 1) => 
  str.split(' ')
    .sort((a, b) => b.length - a.length)
    .slice(0, n);

console.log(findLongestN('The quick brown fox jumps', 3)); 
// ['quick', 'brown', 'jumps']

สรุป

  • Reduce/Loop: O(n) Time, O(1) Space - ดีที่สุดสำหรับหา 1 คำ
  • Sort: O(n log n) Time - เหมาะสำหรับหา Top N
  • ควรจัดการ Punctuation ด้วย Regex \b\w+\b