当前位置:网站首页>【LeetCode】383.赎金信
【LeetCode】383.赎金信
2022-07-31 10:03: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 由小写英文字母组成
题解
使用哈希表存储magazine的所有字符频率
然后遍历ransomNote字符,对应字符的频率做–运算
遇到小于0则为否
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int> mystr;
int len1 = ransomNote.length();
int len2 = magazine.length();
if(len1>len2)
return false;
for(int i=0;i<len2;i++)
{
mystr[magazine[i]]++;
}
for(int i=0;i<len1;i++)
{
mystr[ransomNote[i]]--;
if(mystr[ransomNote[i]]<0)
return false;
}
return true;
}
};
边栏推荐
猜你喜欢
随机推荐
第六章
Gradle series - Groovy overview, basic use (based on Groovy document 4.0.4) day2-1
二叉树的搜索与回溯问题(leetcode)
js空气质量aqi雷达图分析
js implements the 2020 New Year's Day countdown bulletin board
使用turtle画按钮
PyQt5快速开发与实战 9.4 Matplotlib在PyQt中的应用
NowCoderTOP23-27二叉树遍历——持续更新ing
Scala basics [seq, set, map, tuple, WordCount, queue, parallel]
出色的移动端用户验证
(C语言)程序环境和预处理
Day113. Shangyitong: user authentication, Alibaba Cloud OSS, patient management
第二十二课,实例化(instancing)
js以变量为键
GVINS论文阅读笔记
【GORM】存取数组/自定义类型数据
Browser usage ratio js radar chart
csdn文件导出为pdf
Principle of Redis Sentinel
数字加分隔符