LeetCode383. 赎金信

LeetCode383. 赎金信
【简单】
为了不在赎金信中暴露字迹,从杂志上搜索各个需要的字母,组成单词来表达意思。

给你一个赎金信 (ransomNote) 字符串和一个杂志(magazine)字符串,判断 ransomNote 能不能由 magazines 里面的字符构成。

如果可以构成,返回 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 由小写英文字母组成

思路:

把a~z用ASCII码-int('a')表示到0~25
把magazine出现的字符给对应位置++
ransomNote出现的字符给对应位置--,如果小于0了就return false
return true

代码(C++)

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int arr[26] = {0};
        for(int i = 0; i < magazine.size(); i++){
            arr[magazine[i] - 'a']++;
        }
        for(int i = 0; i < ransomNote.size(); i++){
            arr[ransomNote[i] - 'a']--;
            if(arr[ransomNote[i] - 'a'] < 0){
                return false;
            }
        }
        return true;
    }
};

LeetCode383. 赎金信
看了官方题解发现前面加个长度判断更好
而且他的数组是用的vector:vector<int> cnt(26);可以记一下
官方题解:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        if (ransomNote.size() > magazine.size()) {
            return false;
        }
        vector<int> cnt(26);
        for (auto & c : magazine) {
            cnt[c - 'a']++;
        }
        for (auto & c : ransomNote) {
            cnt[c - 'a']--;
            if (cnt[c - 'a'] < 0) {
                return false;
            }
        }
        return true;
    }
};

LeetCode383. 赎金信
但是跑的结果好像没我好。。
python官方题解:

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)

LeetCode383. 赎金信

collections是什么好东西
collections模块
python内建的一个集合模块,提供了许多有用的集合类

  • defaultdict
    LeetCode383. 赎金信
    LeetCode383. 赎金信
    LeetCode383. 赎金信
    没有key就直接返回默认值,int对应默认的值就是0
  • counter
    LeetCode383. 赎金信
    LeetCode383. 赎金信
上一篇:LeetCode_数据结构入门_赎金信


下一篇:LeetCode——383. 赎金信(Java)