在本教程中,我们将学习如何从给定的两个字符串中查找不同的字符。让我们来看一个例子。
输入
string_one = "nhooo" string_two = "tutorialsworld"
输出
d n p w
我们将使用散列来解决该问题。比编写两个嵌套循环更有效
让我们看看解决程序的步骤。
用一些随机值初始化两个字符串。
将映射初始化为map <char,int> chars。
遍历第一个字符串,并将每个字符插入值为1的map中。
现在,遍历第二个字符串。
检查字符是否已经存在。
如果存在,则将其分配为0。
如果不存在,请插入带有值1的字符。
遍历映射并打印值为1的字符。
请参见下面的代码。
#include <bits/stdc++.h>
#include <map>
using namespace std;
void findDistinctCharacters(string one, string two){
// 初始化字符串中的char存在
map<char, int> chars;
// 遍历第一个字符串
for (int i = 0; i < one.size(); ++i){
// 将每个字符插入映射
chars.insert({one[i], 1});
}
// 遍历第二个字符串
for (int i = 0; i < two.size(); ++i){
// 检查当前字符是否在字符串中
if (chars.count(two[i])) {
// 为普通字符分配0
chars.find(two[i])->second = 0;
}
else {
// 插入新字符
chars.insert({two[i], 1});
}
}
// 打印不同的字符
for (auto item: chars){
// 检查存在
if (item.second == 1) {
// 打印不同的字符
cout <<item.first<< " ";
}
}
}
int main(){
string one = "nhooo";
string two = "tutorialsworld";
findDistinctCharacters(one, two);
return 0;
}输出结果
如果运行上面的代码,您将得到以下结果。
d n p w