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

หาคำแรกที่ซ้ำใน String ใน C++

ในปัญหานี้ เราได้รับ string ที่มีคั่นด้วยช่องว่าง งานคือหา คำ (word) แรกที่ซ้ำ

ตัวอย่าง

Input: "C program are easy to program" Output: program

วิธีการแก้ปัญหา: Hash Map (unordered_map)

  1. Split string เป็นคำๆ (ใช้ stringstream)
  2. นับ frequency ของแต่ละคำใน hash map
  3. Traverse คำอีกครั้ง หาคำแรกที่ count > 1

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

#include <bits/stdc++.h>
using namespace std;

string findFirstRepeatedWord(string str) {
    unordered_map freq;
    stringstream ss(str);
    string word;
    
    // Count frequencies
    while (ss >> word) freq[word]++;
    
    // Find first with freq > 1
    stringstream ss2(str);
    while (ss2 >> word) {
        if (freq[word] > 1) return word;
    }
    return "NoRepetition";
}

int main() {
    string str = "C program are easy to program";
    string result = findFirstRepeatedWord(str);
    if (result != "NoRepetition") cout << "First repeated: '" << result << "'";
    else cout << "No word is Repeated";
    return 0;
}

ผลลัพธ์

First repeated word: 'program'