当前位置:网站首页>力扣3_383. 赎金信
力扣3_383. 赎金信
2022-07-04 21:39: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
来源:力扣(LeetCode)
Java解法
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() > magazine.length()) {
return false;
}
int[] cnt = new int[26];//使用计数法
for (char c : magazine.toCharArray()) {
//ToCharArray( )的用法,将字符串对象中的字符转换为一个字符数组。
cnt[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
cnt[c - 'a']--;
if(cnt[c - 'a'] < 0) {
return false;
}
}
return true;
}
}
Python解法1
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
return not collections.Counter(ransomNote) - collections.Counter(magazine)
#这里使用了计数函数collections.Counter()不太容易理解
Python解法2
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
for i in range(len(ransomNote)):
if ransomNote[i] in magazine:
magazine = magazine.replace(ransomNote[i],'',1)
#这里使用了replace()函数,发现一个删除一个
else:
return False
return True
边栏推荐
猜你喜欢
Super detailed tutorial, an introduction to istio Architecture Principle and practical application
Why do you have to be familiar with industry and enterprise business when doing Bi development?
[early knowledge of activities] list of recent activities of livevideostack
close系统调用分析-性能优化
MongoDB聚合操作总结
输入的查询SQL语句,是如何执行的?
【LeetCode】17、电话号码的字母组合
Three or two things about the actual combat of OMS system
QT - plot other problems
HUAWEI nova 10系列发布 华为应用市场筑牢应用安全防火墙
随机推荐
保证接口数据安全的10种方案
# 2156. Find the substring of the given hash value - post order traversal
QT—双缓冲绘图
Super detailed tutorial, an introduction to istio Architecture Principle and practical application
并发网络模块化 读书笔记转
New intersectionobserver usage notes
Machine learning notes mutual information
超详细教程,一文入门Istio架构原理及实战应用
面试题 01.01. 判定字符是否唯一
MongoDB中的索引操作总结
ACM Multimedia 2022 | 视觉语言预训练模型中社会偏见的反事实衡量和消除
Three or two things about the actual combat of OMS system
Golang面试整理 三 简历如何书写
文件读取写入
迷失在Mysql的锁世界
Open3D 曲面法向量计算
大厂的广告系统升级,怎能少了大模型的身影
close系统调用分析-性能优化
AcWing 2022 每日一题
File read write