当前位置:网站首页>力扣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
边栏推荐
- What is the stock account opening process? Is it safe to use flush mobile stock trading software?
- 服装企业为什么要谈信息化?
- Interviewer: what is XSS attack?
- 机器学习笔记 - 互信息Mutual Information
- 283. Moving zero-c and language assisted array method
- TCP协议三次握手过程
- 挖财学院股票开户安全吗?开户只能在挖财开户嘛?
- How to implement Devops with automatic tools
- Shutter textfield example
- 文件读取写入
猜你喜欢

What is business intelligence (BI), just look at this article is enough

Arcgis 10.2.2 | arcgis license server无法启动的解决办法

Exclusive interview of open source summer | new committer Xie Qijun of Apache iotdb community

HUAWEI nova 10系列发布 华为应用市场筑牢应用安全防火墙

迷失在Mysql的锁世界

How was MP3 born?

从RepVgg到MobileOne,含mobileone的代码

TCP shakes hands three times and waves four times. Do you really understand?

CloudCompare&Open3D DBSCAN聚类(非插件式)

Redis03 - network configuration and heartbeat mechanism of redis
随机推荐
服装企业为什么要谈信息化?
VS2019 C# release下断点调试
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
gtest从一无所知到熟练运用(1)gtest安装
Monitor the shuttle return button
Relational database
能源势动:电力行业的碳中和该如何实现?
Nat. Commun.| 机器学习对可突变的治疗性抗体的亲和力和特异性进行共同优化
Golang面试整理 三 简历如何书写
2022 version of stronger jsonpath compatibility and performance test (snack3, fastjson2, jayway.jsonpath)
什么是商业智能(BI),就看这篇文章足够了
i.MX6ULL驱动开发 | 24 - 基于platform平台驱动模型点亮LED
力扣98:验证二叉搜索树
Redis 排查大 key 的3种方法,优化必备
复数在数论、几何中的用途 - 曹则贤
How to implement Devops with automatic tools
历史最全混合专家(MOE)模型相关精选论文、系统、应用整理分享
Analyzing the maker space contained in steam Education
Flutter TextField示例
NAACL-22 | 在基于Prompt的文本生成任务上引入迁移学习的设置