21xrx.com
2025-04-02 03:02:21 Wednesday
文章检索 我的文章 写文章
C++字符串去重技巧
2023-07-01 22:24:49 深夜i     14     0
C++ 字符串 去重 技巧 算法

在C++编程中,字符串去重是一项非常基础的技能,也是很多编程任务中必不可少的一步。在本篇文章中,我们将向大家介绍几种实用的C++字符串去重技巧。

1. 使用stl::set容器

stl::set容器是STL标准库中的一个容器,它被用来实现有序、无重复的数据结构。要去重一个字符串,我们可以将其作为stl::set容器的元素来存储,在遍历结束后再将其转回字符串的形式。

示例代码如下:

#include <iostream>
#include <set>
#include <string>
std::string removeDuplicates(std::string str) {
  std::set<char> charSet;
  for (const char& c : str) {
    charSet.insert(c);
  }
  str = "";
  for (auto it = charSet.begin(); it != charSet.end(); it++) {
    str += *it;
  }
  return str;
}
int main() {
  std::string str = "hello world";
  std::cout << "Original string: " << str << std::endl;
  std::cout << "String after removing duplicates: " << removeDuplicates(str) << std::endl;
  return 0;
}

2. 使用C++11中的算法

在C++11中,引入了新的算法头文件 ,其中的std::unique()函数可以帮助我们快速去重一个字符串。

示例代码如下:

#include <iostream>
#include <algorithm>
#include <string>
std::string removeDuplicates(std::string str) {
  auto newEnd = std::unique(str.begin(), str.end());
  str.erase(newEnd, str.end());
  return str;
}
int main() {
  std::string str = "hello world";
  std::cout << "Original string: " << str << std::endl;
  std::cout << "String after removing duplicates: " << removeDuplicates(str) << std::endl;
  return 0;
}

3. 使用bit位向量

对于字符串中只包含小写字母的情况,我们可以使用bit位向量来实现O(n)时间复杂度的去重操作。我们可以使用一个名为bitmask的unsigned int型变量来表示字符串中的每个字符是否出现过,其中第i位对应着字符i。

示例代码如下:

#include <iostream>
#include <string>
std::string removeDuplicates(std::string str) {
  int size = str.size();
  unsigned int bitmask = 0;
  for (int i = 0; i < size; i++) {
    if ((bitmask & (1 << (str[i] - 'a'))) > 0) {
      str.erase(str.begin() + i);
      size--;
      i--;
    } else
      bitmask |= (1 << (str[i] - 'a'));
    |= (1 << (str[i] - 'a'));
    }
  }
  return str;
}
int main() {
  std::string str = "hello world";
  std::cout << "Original string: " << str << std::endl;
  std::cout << "String after removing duplicates: " << removeDuplicates(str) << std::endl;
  return 0;
}

总结

C++字符串去重是一项非常常用的技巧,在实际的编程中必须牢记。以上所介绍的方法各有优缺点,具体的实现也需要根据实际情况进行选择。希望这篇文章能够对大家有所帮助。

  
  

评论区

请求出错了