任何人都可以完成以下程序吗?
感谢。
void RemoveDuplicates (string& input)
{
string nonRepeatedChars (input);
sort(nonRepeatedChars.begin(), nonRepeatedChars.end());
//cout << nonRepeatedChars <<endl;
string::iterator it = unique(nonRepeatedChars.begin(), nonRepeatedChars.end());
//cout << nonRepeatedChars <<endl;
nonRepeatedChars.erase(it, nonRepeatedChars.end());
cout << "nonRepeatedChars = "<< nonRepeatedChars <<endl;
for(string::iterator i = input.begin(); i != input.end(); i++)
{
cout << "*i = " << *i <<endl;
size_t found = nonRepeatedChars.find(*i);
cout << "found = "<< found <<endl;
if (found != string::npos)
{
input.erase(i);
cout << "input = " << input <<endl;
}
else
{
nonRepeatedChars.erase(found, 1);
cout << "nonRepeatedChars = "<< nonRepeatedChars <<endl;
}
}
cout << "Final Input = " << input <<endl;
}
答案 0 :(得分:2)
解决方案一如既往:
std::string RemoveDuplicates (const std::string& input) {
std::string newT(input);
std::string::iterator it = std::unique(newT.begin(), newT.end());
newT.erase(it, newT.end());
return newT;
}
另一种返回新字符串的解决方案:
std::string RemoveDuplicates (const std::string& input) {
std::string newInput;
const char * prev = nullptr;
for (const auto & ch : input) {
if (!prev || (*prev != ch)) {
newInput.push_back(ch);
}
prev = &ch;
}
return newInput;
}
如果需要的结果是你好 - &gt; helo 然后解决方案是:
std::string RemoveDuplicates (const std::string& input) {
std::string newInput;
std::set<char> addedChars;
for (const auto & ch : input) {
if (addedChars.end() == addedChars.find(ch)) {
newInput.push_back(ch);
addedChars.insert(ch);
}
}
return newInput;
}
如果您需要保存字符顺序并删除重复项:
Theme.Material