ในปัญหานี้ เราเป็นสตริง str ที่ประกอบด้วยคำที่คั่นด้วยจุลภาค งานของเราคือ ค้นหาคำที่ซ้ำคำแรกในสตริง .
เราต้องหาคำว่า 'string between two spaces' คำแรกที่ซ้ำกันใน string
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
Input : str = "C program are easy to program" Output : program
แนวทางการแก้ปัญหา
วิธีแก้ปัญหาอย่างง่ายคือการใช้โครงสร้างข้อมูลแฮชแมป ในการค้นหาคำที่ซ้ำคำแรก เราจะเก็บแต่ละคำและจำนวนคำนั้น (จำนวนครั้งที่ปรากฏในสตริง ) ใน hashmap สำหรับสิ่งนี้เราจะตรวจสอบต่อไปว่าคำปัจจุบันมีอยู่หรือไม่
จากนั้นเราจะพิมพ์งานแรกที่มีจำนวนมากกว่าหนึ่งรายการในแฮชแมป
ตัวอย่าง
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
#include <bits/stdc++.h>
using namespace std;
string findFirstRepeatWord(string str){
istringstream iss(str);
string word;
unordered_map<string, int> wordCountMap;
while (getline(iss, word, ' ')) {
if (wordCountMap.find(word) != wordCountMap.end())
wordCountMap[word] ++;
else
wordCountMap.insert(make_pair(word, 1));
}
istringstream iss2(str);
while (getline(iss2, word, ' ')) {
int count = wordCountMap[word];
if (count > 1) {
return word;
}
}
return "NoRepetition";
}
int main(){
string str = "C program are easy to program";
string repeatedWord = findFirstRepeatWord(str);
if (repeatedWord != "NoRepetition")
cout<<"The first repeated word is '"<<repeatedWord<<"'";
else
cout<<"No word is Repeated in the string";
return 0;
} ผลลัพธ์
The first repeated word is 'program'
โปรแกรมนี้ใช้ฟังก์ชันในตัวจำนวนมากเพื่อให้งานง่ายขึ้น