📜  在std :: vector中查找并打印重复的单词<string>使用STL函数

📅  最后修改于: 2021-05-30 10:46:01             🧑  作者: Mango

考虑一个字符串数组,并在该数组中查找重复的单词,并打印重复的单词(如果存在)。
例子:

Input : { "welcome", "to", "geeks", "for", "geeks" }
Output : geeks

Input : { "reduce", "reuse", "recycle", "reduce", 
          "reuse", "recycle", " recycle" }
Output : recycle
reduce
reuse

Input : { "Go", "Green" }
Output : No Duplicate words

方法1(使用排序)
1.对字符串数组进行排序。
2.比较字符串数组中的相邻单词。
3.如果两个单词相同,则将该单词推入另一个向量字符串。
4.打印重复的单词(如果存在)。

CPP
// CPP program to find duplicate word in a
// vector
#include 
using namespace std;
 
void printDuplicates(vector words)
{
    vector duplicate;
 
    // STL function to sort the array of string
    sort(words.begin(), words.end());
 
    for (int i = 1; i < words.size(); i++) {
        if (words[i - 1] == words[i]) {
 
            // STL function to push the duplicate
            // words in a new vector string
            if (duplicate.empty())
              duplicate.push_back(words[i]);
            else if (words[i] != duplicate.back())
                duplicate.push_back(words[i]);
        }
    }
 
    if (duplicate.size() == 0)
        cout << "No Duplicate words" << endl;
    else
        for (int i = 0; i < duplicate.size(); i++)
            cout << duplicate[i] << endl;
}
 
// Driver code
int main()
{
    vector words{ "welcome", "to", "geeks", "for",
                          "geeks",   "to", "geeks" };
    printDuplicates(words);
    return 0;
}


CPP
// CPP program to find duplicate word in a
// vector
#include
using namespace std;
 
void printDuplicates(vector words)
{
    unordered_set s;
 
    bool dupFound = false;
    for (int i = 1; iwords{ "welcome", "to", "geeks",
                                  "for", "geeks" };
    printDuplicates(words);
    return 0;
}


输出
geeks
to

方法2(使用哈希)
1.创建一个空的哈希表。
2.一遍遍的单词。
3.对于每个单词,检查哈希中是否已经存在。
……..if(已经存在于哈希中)
…………。打印文字
……..别的
…………。将单词插入哈希。

CPP

// CPP program to find duplicate word in a
// vector
#include
using namespace std;
 
void printDuplicates(vector words)
{
    unordered_set s;
 
    bool dupFound = false;
    for (int i = 1; iwords{ "welcome", "to", "geeks",
                                  "for", "geeks" };
    printDuplicates(words);
    return 0;
}

输出:

geeks
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”