c++删除重复字符的方法是什么

avatar
作者
猴君
阅读量:0

在C++中删除重复字符的一种方法是使用哈希表。可以使用一个数组或者一个标准库中的unordered_set来实现哈希表。具体步骤如下:

  1. 遍历字符串的每个字符。
  2. 检查当前字符是否已经在哈希表中存在。
  3. 如果当前字符不存在于哈希表中,将其加入哈希表,并将其添加到新的字符串中。
  4. 如果当前字符已经存在于哈希表中,说明是重复字符,跳过该字符。
  5. 最终得到的新字符串就是删除重复字符后的结果。

以下是一个使用unordered_set的示例代码:

#include <iostream> #include <unordered_set> #include <string>  std::string removeDuplicates(const std::string& str) {     std::string result;     std::unordered_set<char> uniqueChars;      for (char c : str) {         if (uniqueChars.find(c) == uniqueChars.end()) {             uniqueChars.insert(c);             result += c;         }     }      return result; }  int main() {     std::string input = "abracadabra";     std::string result = removeDuplicates(input);     std::cout << result << std::endl;  // 输出 "abrcd"     return 0; } 

注意:这种方法会保留第一次出现的字符,删除其余重复的字符。如果要保留最后一次出现的字符,可以将哈希表的类型改为std::unordered_map<char, int>,将字符映射到它们在字符串中的索引位置。在遍历字符串时,更新哈希表中字符的索引值。在最后,遍历哈希表,将索引值最大的字符添加到结果字符串中。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!