给定一个字符串,我们必须从该字符串删除所有重复/重复的单词。
例子:
Input: str = “Geeks for Geeks A Computer Science portal for Geeks”
Output: Geeks for A Computer Science portal
Explanation: here ‘Geeks’ and ‘for’ are duplicate so these words are removed from the string
Input: “Publish your own articles on GeeksforGeeks and share your knowledge with the world”
Output: Publish your own articles on GeeksforGeeks and share knowledge with the world
Explanation: here ‘your’ is the duplicate word so that word is removed from string
我们创建一个空的哈希表。然后在空格周围分割给定的字符串。对于每个单词,我们首先检查它是否在哈希表中。如果在哈希表中找不到,我们将其打印并存储在哈希表中。
要将给定的字符串拆分成单词,我们在C++中使用stringstream。
// C++ program to remove duplicate
// word from string
#include
using namespace std;
void removeDupWord(string str)
{
// Used to split string around spaces.
istringstream ss(str);
// To store individual visited words
unordered_set hsh;
// Traverse through all words
do
{
string word;
ss >> word;
// If current word is not seen before.
while (hsh.find(word) == hsh.end()) {
cout << word << " ";
hsh.insert(word);
}
} while (ss);
}
// Driver function
int main()
{
string str = "Geeks for Geeks A Computer"
" Science portal for Geeks";
removeDupWord(str);
return 0;
}
输出:
Geeks for A Computer Science portal
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。