কম্পিউটার টিউটোরিয়াল

স্ট্রিংয়ে ডুপ্লিকেট শব্দ খুঁজে বের করা - JavaScript

একটি স্ট্রিংয়ে একাধিকবার আবির্ভূত শব্দগুলো বের করে একটি স্ট্রিং আকারে রিটার্ন করা।

উদাহরণ

"big black bug bit a big black dog on his big black nose"
// ডুপ্লিকেট শব্দ: "big" (৩ বার), "black" (৩ বার)
// ফলাফল: "big black"

সমাধান

const findDuplicateWords = (str) => {
  const words = str.split(' ');
  const seen = new Set();
  const duplicates = new Set();
  
  for (const word of words) {
    if (seen.has(word)) {
      duplicates.add(word);
    } else {
      seen.add(word);
    }
  }
  
  return [...duplicates].join(' ');
};

// ফাংশনাল পদ্ধতি
const findDuplicateWordsFP = (str) => {
  return str
    .split(' ')
    .filter((word, index, arr) => arr.indexOf(word) !== index)
    .filter((word, index, arr) => arr.indexOf(word) === index)
    .join(' ');
};

// টেস্ট
const str = "big black bug bit a big black dog on his big black nose";
console.log(findDuplicateWords(str));      // "big black"
console.log(findDuplicateWordsFP(str));    // "big black"

// কেস-ইনসেনসিটিভ
const findDuplicateWordsCI = (str) => {
  const words = str.toLowerCase().split(' ');
  const seen = new Set();
  const duplicates = new Set();
  
  for (const word of words) {
    if (seen.has(word)) duplicates.add(word);
    else seen.add(word);
  }
  
  return [...duplicates].join(' ');
};

পারফরম্যান্স তুলনা

পদ্ধতি সময় জটিলতা স্থান জটিলতা
Set (দুটি) O(n) O(n)
filter + indexOf O(n²) O(n)
Map (ফ্রিকোয়েন্সি) O(n) O(n)

উৎপাদন

big black
  1. জাভাস্ক্রিপ্টে স্ট্রিংয়ের হ্যামিং দূরত্ব (Hamming Distance) বের করা

  2. জাভাস্ক্রিপ্টে স্ট্রিংয়ে ন্যূনতম ডিলিশন করে আডজেসেন্ট ক্যারেক্টার ভিন্ন করা

  3. জাভাস্ক্রিপ্টে স্ট্রিং-এ থাকা শব্দগুলো উল্টো করা

  4. জাভাস্ক্রিপ্টে টেক্সট স্ট্রিংয়ে 탑 ৩ সবচেয়ে বেশি ফ্রিকোয়েন্ট শব্দ খুঁজে বের করা