Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm từ lặp đầu tiên trong chuỗi C++


Cho chuỗi str gồm các từ cách nhau bởi dấu cách. Nhiệm vụ: tìm từ lặp lại đầu tiên trong chuỗi.

Ví dụ minh họa

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

Phương pháp giải

Dùng unordered_map đếm số lần xuất hiện của mỗi từ. Duyệt lại chuỗi, từ đầu tiên có count > 1 là kết quả.

Ví dụ chương trình

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

string findFirstRepeatWord(string str){
    istringstream iss(str);
    string word;
    unordered_map<string, int> wordCount;
    while (getline(iss, word, ' ')) wordCount[word]++;
    
    istringstream iss2(str);
    while (getline(iss2, word, ' ')) {
        if (wordCount[word] > 1) return word;
    }
    return "Không có từ lặp";
}

int main(){
    string str = "C program are easy to program";
    string repeated = findFirstRepeatWord(str);
    if (repeated != "Không có từ lặp")
        cout << "Từ lặp đầu tiên: '" << repeated << "'";
    else cout << "Không có từ lặp";
    return 0;
}

Kết quả

Từ lặp đầu tiên: 'program'