我知道我的问题对某些人来说可能是愚蠢的,但我整天用Google搜索并尝试制作我自己的解决方案,但我失败了..请帮助..
我需要从一个简单的字符串数组中打印所有uniqe字符串。
示例:
输入:“嗨”“我的”“名字”“嗨”“土豆”“文字”“名字”“嗨”
输出:“我的”“土豆”“文字”
我只使用一次打印所有功能(“嗨”,“我的”,“名字”,“马铃薯”,“文本”),但我需要忽略数组中2倍以上的所有内容。
我的algorythm是: 1.按bubblesort排序
.. if(array [i]!= array [i + 1])// make something ...
答案 0 :(得分:1)
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<std::string> v = {
"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi",
};
sort(v.begin(), v.end());
for (auto a = v.begin(), b = a; a != v.end(); a = b) {
b = find_if(b, v.end(), [&](string s) {return *b != s;});
if (distance(a, b) == 1)
cout << *a << '\n';
}
}
答案 1 :(得分:0)
更新:我误解了这个问题,现在它在问题中作为输出 只是你可以计算每个字符串的出现次数,并只打印出现的字符串。 时间复杂度:O(N ^ 2) 这是代码
#include<iostream>
#include<set>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n; // number of strings you want in your array
cin >> n;
string t; // get t and push back it in the vector
vector <string> words; //we use vector to store as we will push back them
for(size_t i = 1;i <= n;i++)
{
cin >> t;
words.push_back(t);
}
for(int i = 0;i < words.size();i++)
{
int cnt = 0;
for(int j = 0;j < words.size() && cnt < 2;j++)
{
if(words[i] == words[j])
cnt++;
}
if(cnt == 1) //its unique..print it
cout << words[i] <<endl;
}
}
答案 2 :(得分:0)
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi"};
std::sort(words.begin(), words.end());
for (auto curr = words.begin(); curr != words.end(); ) {
// If working w/ few duplicate words:
auto next = std::find_if(
curr + 1, words.end(), [&](const auto& s) { return s != *curr; }
);
/* If working w/ many duplicate words:
auto next = std::upper_bound(curr + 1, words.end(), *curr); */
if (std::distance(curr, next) == 1) {
std::cout << *curr++ << '\n';
} else {
curr = next;
}
}
}
答案 3 :(得分:0)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi"};
std::vector<std::string> out;
std::sort(words.begin(), words.end());
std::unique_copy(words.begin(), words.end(), std::back_inserter(out));
std::set_difference(words.begin(), words.end(), out.begin(), out.end(), std::ostream_iterator<std::string>(std::cout, " "));
}
注意:未经测试,因为我在手机上和床上写这篇文章。