给定一个字符串,我如何才能只添加另一个字符串中的唯一字符
Given a string, how can I add only unique characters from another string to it?
我已经尝试了很多不同的东西好几个小时了,我尝试使用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
。
这是一个指南。你必须做的工作
- 然后连接两个字符串
- 删除重复项
以下是如何删除重复
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),即与原始阵列长度成线性关系。
相关文章:
- 如何将字符串添加到布谷鸟过滤器?
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 如何在C++中为字符串添加字符?
- 在特定位置为字符串添加空格
- 有没有办法将字符串添加到 Vector 中,但前提是它尚不存在?->C++
- 是什么使这个以'+'开头的字符串添加成为有效的语句?
- 如何使用函数将字符串添加到向量中
- 如何在 c++ 中将字符串添加到动态数组?
- 向字符串添加字符
- 向字符串添加位值
- 如何从用户那里接收多个字符串并将这些字符串添加到 c++ 中的数组中?
- 字符串添加数字 C++
- std::字符串添加到字符*
- C++ 向字符串添加"u"
- JSONCPP正在向字符串添加额外的双引号
- C 将N字符串添加到字符串流中
- 以简单且更少的代码方式将字符串添加在一起
- 字符串添加或减法操作员
- 将字符串添加到2D数组并显示COUT消息(没有错误消息?)的错误
- 如何使用递归向字符串添加逗号