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

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

ภาพรวม

บทความนี้สาธิตวิธีหาความยาวของคำที่สองสั้นที่สุดในประโยค เช่น 'This is a sample string' -> คำสั้นที่สุด 'a' (1) คำสองสั้นที่สุด 'is' (2) -> ผลลัพธ์ 2

การนำไปใช้

const secondSmallest = (str) => {
  const words = str.split(' ');
  if (words.length < 2) return false;
  
  const lengths = words.map(w => w.length);
  lengths.sort((a, b) => a - b);
  return lengths[1];
};

console.log(secondSmallest('This is a sample string')); // 2

ผลลัพธ์

2

Edge Cases ที่ควรจัดการ

  • Multiple Spaces: ใช้ `split(/\s+/)`
  • Punctuation: 'word,' ความยาว 5 หรือ 4?
  • Empty String: คืน false หรือ 0
  • Single Word: คืน false
  • Duplicate Lengths: [2, 2, 3] -> Second smallest = 2

วิธีการทันสมัย (Robust)

const secondSmallestWordLength = (str) => {
  // แยกคำด้วย regex, ตัด punctuation
  const words = str.toLowerCase().match(/\b\w+\b/g) || [];
  if (words.length < 2) return null;
  
  const lengths = [...new Set(words.map(w => w.length))].sort((a, b) => a - b);
  return lengths[1] ?? null; // ความยาวที่ 2 สั้นที่สุด (Unique Lengths)
};

// หรือถ้ารวม Duplicate Lengths
const secondSmallestInclDupes = (str) => {
  const words = str.match(/\b\w+\b/g) || [];
  if (words.length < 2) return null;
  return words.map(w => w.length).sort((a, b) => a - b)[1];
};

One-pass Algorithm (O(n) Time, O(1) Space)

const secondSmallestOnePass = (str) => {
  const words = str.match(/\b\w+\b/g) || [];
  if (words.length < 2) return null;
  
  let min1 = Infinity, min2 = Infinity;
  
  for (const word of words) {
    const len = word.length;
    if (len < min1) {
      min2 = min1;
      min1 = len;
    } else if (len < min2 && len !== min1) {
      min2 = len;
    }
  }
  
  return min2 === Infinity ? null : min2;
};

การประยุกต์ใช้

  • Text Analysis: Word Length Statistics
  • Readability Metrics
  • NLP Preprocessing
  • Code Golf / Algorithm Challenges