当前位置:网站首页>【LeetCode 383】赎金信
【LeetCode 383】赎金信
2022-04-21 06:20:00 【别偷我能量】
题目介绍
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
示例1
输入:ransomNote = "a", magazine = "b"
输出:false
示例2
输入:ransomNote = "aa", magazine = "ab"
输出:false
示例3
输入:ransomNote = "aa", magazine = "aab"
输出:true
提示
- 1 <= ransomNote.length, magazine.length <= 105
- ransomNote 和 magazine 由小写英文字母组成
思路
此题的思路和【LeetCode 350 两个数组的交集 II】一毛一样,核心都是利用哈希表的思想。将magazine中的字母和其出现的次数分别存储起来,再去遍历ransomNote中的字母,进行判断,若出现次数>0,则对其出现的次数-1,遍历下一个字母;若出现的次数==0,则说明 ransomNote 能不能由 magazine 里面的字符构成,返回flase。
1.一维数组实现
bool canConstruct(string ransomNote, string magazine) {
int a[123]={
0};//小写英文字母z的ascii值122
for(char x:magazine)
a[int(x)]++;
for(char y:ransomNote){
if(a[int(y)]>0)
a[int(y)]--;
else
return 0;
}
return 1;
}
2.哈希表实现
bool canConstruct(string ransomNote, string magazine){
unordered_map<char,int>a; //将magazine中的字母和其出现次数分别存储起来
for(char x:magazine)
a[x]++;
for(char y:ransomNote){
if(a[y]>0)
a[y]--;
else
return 0;
}
return 1;
}
在内存消耗上,数组实现要比哈希表实现低一些。
版权声明
本文为[别偷我能量]所创,转载请带上原文链接,感谢
https://blog.csdn.net/mitongxue/article/details/123888104
边栏推荐
- CF6D Lizards and Basements 2题解
- Linux启动MySQL报错
- 6 service and ingress
- Draw QQ charts with different distribution
- 记录tx2上安装配置gestermer进而使用gst-rtsp-server
- 【ThreadX】H743ZI+LAN8720+ThreadX+NetX Duo移植
- 用JS函數形式實現一個Array.prototype.forEach(),.map(),.filter()
- Chapter 5 support vector machine (SVM)
- 解决replace遍历循环调用,导致后续的replace替换掉前面replace的数据的问题
- This site cannot provide a secure connection. An unsupported protocol is used
猜你喜欢

MySQL Workbench cannot use clear text authentication over non-ssl connections 问题解决

Official account version update and introduction
【ThreadX】H743ZI+LAN8720+ThreadX+NetX Duo移植

Write tweets for one year and share five commonly used writing software

为短路运算符布尔表达式添加括号

【WPF】笔记

MySql分组 按某个字段排序取值第一条

2020杭电多校赛第四场1007 Go Running(hdu6808)
![[SSM integration] 4 Logic code writing and testing](/img/0b/5745b18ae8ee5db7b36dbb7c8d0bdd.png)
[SSM integration] 4 Logic code writing and testing

Simultaneous access of computer intranet and extranet - solution
随机推荐
yolov5的onnx模型去除transpose层
applicationContext. How to solve the problem of XML becoming gray document
[LabVIEW] record some pits in LabVIEW project
跨域问题-Allow-Origin header contains multiple values... but only one is allowed
什么是PaaS?平台即服务介绍
使用redis实现分布式锁原理代码浅析
Learn SCI paper drawing skills (b)
SQL--数据的过滤和分组
【ThreadX】H743+ThreadX+FileX移植记录
Busybox initrd及初始化流程
Vee validate validation
【STM32&LWIP】记录一次诡异的ping不通的解决方法
记一次mySQL慢sql优化
Chapter 5 support vector machine (SVM)
If I use Monet's color matching in scientific research pictures?
Pm2 部署 Nuxt 相关命令
高级系统设置点击无反应,打不开的解决办法
[STM32 & LwIP] record the solution of a strange Ping failure
做一款自己的小程序
Build your own blog