当前位置:网站首页>力扣每日一题-第50天-383. 赎金信
力扣每日一题-第50天-383. 赎金信
2022-08-08 23:13:00 【重邮研究森】
2022.8.8今天你刷题了吗?
题目:
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
分析:
给定两个字符串,需要判断2号字符串是否包含了1号字符串,嗯,就是这么简单。
思路:直接在2号字符串中进行查找1号字符串,也就是遍历一次一号字符串,然后遍历时判断2号中有没有,如果没有直接返回false,如果有,则把该字符串替换,这样防止下次重复判断。
解析:
1.查找法
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for (auto i = 0; i < ransomNote.size(); i++)
{
int pos = magazine.find(ransomNote[i]);
if (pos!=-1)
{
magazine[magazine.find(ransomNote[i])] = ' ';
}
else
{
return false;
}
}
return true;
}
};2.计数法
官方的写法是:先把2号字符串中的26个字母的次数记下来,然后我们开始遍历一号字符串,如果1号字符串存在某一个元素,那么2号字符串中该元素次数-1,然后判断-1之后次数是否<0,也就是没有了
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> vec(26);
for (auto &ch : magazine)
{
vec[ch - 'a']++;
}
for (auto& ch : ransomNote)
{
vec[ch - 'a']--;
if (vec[ch - 'a'] < 0)
{
return false;
}
}
return true;
}
};边栏推荐
- Virtualization type (with picture)
- 最详树莓派4B装机流程及ifconfig不到wlan0的解决办法
- You know you every day in the use of NAT?
- Porting ucos2 code from stm32 to GD32
- 【Pytorch】学习笔记(一)
- Modal dialog is used to implement the sign-in
- (newcoder 15079)无关(容斥原理)
- WeChat applet wx:for loop output example
- 【Verilog基础】PPA优化问题总结(含面积优化、速度优化)
- (nowcoder22529C)dinner(容斥原理+排列组合)
猜你喜欢

树莓派wiringPi库的使用补充

Introduction to Qt (5) - file operation, hotkey and mouse reading (implementation of txt window)

【Bug解决】ValueError: Object arrays cannot be loaded when allow_pickle=False

JS中的作用域与作用域链

深拷贝与浅拷贝

You know you every day in the use of NAT?

(2022牛客多校五)G-KFC Crazy Thursday(二分+哈希/Manacher)

Use Mongoose populate to implement multi-table associative storage and query, with complete code included

Qt入门(五)——文件操作、热键和鼠标的读取(txt窗口的实现)

Analysis of WLAN - Wireless Local Area Network
随机推荐
考证必看 | PMP扫盲贴+PMP材料
STM8L 液晶数码管驱动,温度计液晶屏显示
JSDay1-两数之和
用模态框 实现 注册 登陆
2022牛客多校六 M-Z-Game on grid(动态规划)
请问:支付宝上买基金安全吗
树莓派wiringPi库的使用补充
JSDay2-两个数组的交集
详解JS中for...of、in关键字
Excuse me: is it safe to pay treasure to buy fund on
stm32 uses spi1 to read data from dma in slave mode
2022杭电多校六 1006-Maex (树形DP)
Introduction to Qt (5) - file operation, hotkey and mouse reading (implementation of txt window)
WeChat applet develops some function usage methods
wps a3格式怎么转换成a4?wps a3格式转换成a4的方法
ndk和JNI的使用初探
flutter 书写json解析类
word文档标题怎么自动编号?
(2022牛客多校五)G-KFC Crazy Thursday(二分+哈希/Manacher)
Hi3516 use wifi module