给定一个字符串,我如何才能只添加另一个字符串中的唯一字符

Given a string, how can I add only unique characters from another string to it?

本文关键字:字符串 添加 另一个 字符 唯一 一个      更新时间:2023-10-16

我已经尝试了很多不同的东西好几个小时了,我尝试使用std::unique,但我得到了奇怪的结果,然后我尝试使用string::find。我觉得如果我使用std::vector会很容易实现这一点我正在寻找一种使用标准库的有效方法,我在这里和cpluplus.com上读到了很多关于这个主题的问题,但我无法使用他们的答案来实现我需要的东西。如果这是微不足道的,我很抱歉,但我已经厌倦了在这一点上尝试不同的事情。

例如:

int main(){
  std::string unique_chars;
  std::string new_string = "ABC"
  getUniqueChars(unique_chars, new_string);
  cout << unique_chars << endl;
  new_string = "ABDF"
  getUniqueChars(unique_chars, new_string);
  cout << unique_chars; 
  return 0;
}  
void getUniqueChars(string &unique_chars, string &new_string){
   //add only unique characters from new_string to unique_chars
   return;
}

应输出:

ABC
ABCDF

您可以使用std::set来完成此操作。将两个字符串中的所有字符添加到集合中,然后从集合中创建一个新字符串。

// Create a set of characters from `unique_str`
std::set<char> set(unique_chars.begin(), unique_chars.end());
// Insert the characters from `new_string`
set.insert(new_string.begin(), new_string.end());
// The set now contains only unique characters from both strings, no duplicates
// Convert back to a string
unique_chars = std::string(set.begin(), set.end());

如果您有一个支持C++11的编译器和标准库,并且不希望对结果进行排序,那么您可以使用std::unordered_set

这是一个指南。你必须做的工作

  1. 然后连接两个字符串
  2. 删除重复项

以下是如何删除重复

std::sort(str.begin(), str.end()); str.erase(std::unique(str.begin(), str.end()), str.end());

我想,一种方法是:

Algorithm:

取原始字符串并根据每个字符将其散列到散列表中。

从新字符串中提取每个字符,并检查哈希表bucket是否已经标记。

如果未标记,请将其附加到原始字符串中,否则将拒绝它。

Code(not tested):
string orig, new ;
char arr[26]={initialise with all alphabets}
for(int i=0;i<orig.size();i++)
arr[new[i]] = x;
for(int i=0;i<new.size();i++)
if(arr[new[i]] != x)
orig += new[i];

复杂度(用于预处理)将是O(N),即与原始阵列长度成线性关系。