朴素方法直接查:
#include <iostream>
using namespace std;
string s1, s2;
bool check_exists(char c){
for(auto a : s2){
if(a == c)
return true;
}
return false;
}
int main(){
getline(cin, s1);
getline(cin, s2);
string res;
for(auto c : s1){
if(!check_exists(c))
res += c;
}
cout << res << endl;
}
优化:
判断某个元素是否在某个集合出现过->哈希表 O(1)复杂度
#include <iostream>
#include <unordered_set>
using namespace std;
string s1, s2;
int main()
{
getline(cin, s1);
getline(cin, s2);
unordered_set<char> hash; // 定义哈希表
for (auto c : s2) hash.insert(c); // 将s2中的字符插入哈希表
string res;
for (auto c : s1)
if (!hash.count(c)) //count 统计哈希表中c的个数
res += c;
cout << res << endl;
return 0;
}