Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c++ - Remove all duplicate characters from a string (STL)

Can anyone complete the following program?

Thanks.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution simple as always:

void RemoveDuplicates (std::string& input) {
  std::string::iterator it = std::unique(input.begin(), input.end());
  input.erase(it, input.end());
  std::cout << "New input = "<< input << std::endl;
}

Another solution to return a new string:

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;
}

If desired result is hello -> helo then the solution is :

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;
}

If you need to save order of chars and remove duplicates:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...