原题链接:1050 String Subtraction (20分)
题目大意:
给你一行串 A,一行串 B。如果 A 中存在 B 里有的单词,要将其删掉,不改变 A 其他的内容。
分析:
可以直接暴力:用 string 读入,然后遍历 A 的时候,在 B 中依次查找。
或者,使用 C++ 11 中自带的哈希表。
#include <unordered_set>
unordered_set<char> hash
将 B 中每个字符存入 hash 中,每次遍历 A 的时候,只需要在 hash 查找 B 中字符的映射就好了。
有序:
set和map是不允许出现重复元素的,基于平衡树实现的
一系列操作都是:O(logn)
multiset s,multimap<int, int> m;
multiset, multimap是允许出现重复元素的,
无序:
unordered_set,unordered_map,unordered_multiset,unordered_multimap
满分代码(暴力):
#include <iostream>
#include <string.h>
#include <algorithm>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 1e3+10;
string s1, s2;
PAT暴力就可以过
bool check_exists(char c) {
for(auto a: s2)
if(c == a) {
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;
return 0;
}
满分代码(哈希表):
#include <iostream>
#include <string.h>
#include <unordered_set>
#include <algorithm>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 1e3+10;
string s1, s2;
/*
判断某个元素是否在某集合出现过
哈希表可以使增删改查的复杂度都是O(1)
hash.insert
hash.count
*/
int main() {
getline(cin, s1);
getline(cin, s2);
string res;
unordered_set<char> hash; // 定义一个hash表
for(auto c: s2) hash.insert(c); // 将s2中的字符插入
for(auto c: s1)
if(!hash.count(c)) {
res += c;
}
cout << res << endl;
return 0;
}