383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

思路:
这是LeetCode Discuss中的最热代码,它的原理就是列出了magazine的字母表,然后算出了出现个数,然后遍历ransomNote,保证有足够的字母可用,代码非常清晰。

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] arr = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
            arr[magazine.charAt(i) - 'a']++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            if(--arr[ransomNote.charAt(i)-'a'] < 0) {
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 示例 1: 输入:ransomNote = "a", magazine = "b" 输出:false 示例 2: 输入:ransomNote = "aa", magazine = "ab" 输出:false 示例 3: 输入:ransomNote = "aa", magazine = "aab" 输出:true 提示: 你可以假设两个字符串均只含有小写字母。 ### 回答2: 首先,我们可以遍历 magazine 字符串,统计每个字符出现的频次,存储在一个字典中。 然后,再遍历 ransomNote 字符串,对于每个字符,在字典中找到对应的频次,并将其减1。如果字典中不存在对应的字符,或者频次为0,即无法从 magazine 中组成 ransomNote,则返回 false。 最后,如果遍历 ransomNote 完毕且所有字符都能从 magazine 中组成,则返回 true。 算法步骤如下: 1. 初始化一个空字典 counts,用于存储 magazine 中每个字符的频次。 2. 遍历 magazine 字符串中的每个字符,将字符作为键,频次作为值,存储在 counts 中。如果字典中已存在该字符,则将对应的频次加1;否则,将该字符作为键,频次初始化为1。 3. 遍历 ransomNote 字符串中的每个字符,对于每个字符: - 如果该字符不在字典 counts 中,返回 false。 - 如果该字符在字典 counts 中,但对应的频次为0,返回 false。 - 如果该字符在字典 counts 中,且对应的频次大于0,则将频次减1。 4. 如果遍历完 ransomNote 字符串并且都能够从 magazine 中组成,则返回 true;否则,返回 false。 以下为具体的代码实现: ```python def canConstruct(ransomNote: str, magazine: str) -> bool: counts = {} for char in magazine: if char in counts: counts[char] += 1 else: counts[char] = 1 for char in ransomNote: if char not in counts or counts[char] == 0: return False counts[char] -= 1 return True ``` 通过以上算法,我们可以判断 ransomNote 是否能够由 magazine 中的字符构成。 ### 回答3: 计算字符出现次数的方法: 1. 遍历 magazine 字符串,记录每个字符出现的次数,存储在字典 mag_dict 中。 2. 遍历 ransomNote 字符串,判断每个字符是否在 mag_dict 中,并且对应字符的出现次数是否大于等于 ransomNote 中该字符的出现次数。 - 若有字符不在 mag_dict 中或者该字符的出现次数小于 ransomNote 中该字符的出现次数,则返回 false。 3. 若遍历完成后没有返回 false,则返回 true。 代码如下所示: ```python def canConstruct(ransomNote: str, magazine: str) -> bool: mag_dict = {} for c in magazine: if c in mag_dict: mag_dict[c] += 1 else: mag_dict[c] = 1 for c in ransomNote: if c in mag_dict and mag_dict[c] >= ransomNote.count(c): continue else: return False return True ``` 以上的方法时间复杂度为 O(n+m),其中 n 和 m 分别是 ransomNote 和 magazine 的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值