PAT 甲级 1050 String Subtraction (20分) 哈希表

原题链接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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值