![](/img/trans.png)
[英]Given a set of characters, how can you display the string with a higher lexicographical order, only by rearranging the characters?
[英]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:
取原始字符串,并根据每个字符将其哈希到哈希表中。
从新字符串中获取每个字符,并检查是否已标记哈希表存储桶。
如果未标记,则将其附加到原始字符串,否则拒绝它。
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),即与原始数组长度成线性关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.