朴素方法直接查:
#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;
}
本文介绍使用两种方法从一个字符串中去除所有在另一个字符串中出现的字符。第一种方法通过遍历检查,第二种方法利用哈希表实现O(1)时间复杂度的查找。
357

被折叠的 条评论
为什么被折叠?



