【问题标题】:Remove all duplicate characters from a string (STL)从字符串中删除所有重复字符 (STL)
【发布时间】:2017-04-30 08:37:53
【问题描述】:

任何人都可以完成以下程序吗?

谢谢。

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

【问题讨论】:

  • 欢迎来到 StackOverflow。请拨打tour,学习提出好问题stackoverflow.com/help/how-to-ask。如果您正在寻求有关调试代码的帮助,请参阅 ericlippert.com/2014/03/05/how-to-debug-small-programs 这个问题需要更多详细信息,以避免出现“请解决我的问题”的印象。或“请做我的功课。”您可能还想了解格式化以提高可读性。
  • 输入是“bbccdddaaba”。预期的输出是“bcda”

标签: c++ stl


【解决方案1】:

解决方案一如既往的简单:

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

另一种返回新字符串的解决方案:

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

如果想要的结果是 hello -> helo 那么解决方案是:

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

如果您需要保存字符顺序并删除重复项:

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

【讨论】:

  • 如果 OP 不希望对 input 进行排序怎么办?
  • @Rakete1111:在这种情况下,他应该添加 const std::string& 以表明他的意图并添加到此函数的返回值。现在不是纯函数,而是有副作用的函数
  • 是的,该函数有副作用:删除input的重复项。但仅此而已。无论如何它都不应该修改input。顺序必须相同。您的第二个解决方案有同样的问题。
  • @Rakete1111:检查我提供的另一个版本。如果用户不提供 const 引用,则意味着用户想要修改此字符串,否则它提供 const 引用
  • 这不是我的意思。 OP 想要什么:hello => helo。你的功能做什么:hello => ehlo
猜你喜欢
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
相关资源
最近更新 更多