LeetCode刷题——383. 赎金信(简单)——字符统计

我的写法:建立map查表

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        map<char,int> content;
        for(char a:magazine){
            content[a]++;
        }


        for(auto begin=ransomNote.cbegin();begin<ransomNote.cend();++begin){
            if(content[*begin]==0){
                return false;
            }else{
                content[*begin]--;
            }
        }

        return true;

    }
};

官方解法:字符统计

        题目要求使用字符串magazine 中的字符来构建新的字符串 ransomNote,且ransomNote 中的每个字符只能使用一次,只需要满足字符串magazine 中的每个英文字母 (’a’-’z’) 的统计次数都大于等于 ransomNote 中相同字母的统计次数即可

        如果字符串magazine 的长度小于字符串 ransomNote 的长度,则我们可以肯定 magazine 无法构成 ransomNote,此时直接返回false。
        首先统计magazine 中每个英文字母 a的次数 cnt[a],再遍历统计ransomNote 中每个英文字母的次数,如果发现ransomNote 中存在某个英文字母 c 的统计次数大于magazine 中该字母统计次数 cnt[c],则此时我们直接返回 false。

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;
    }
};

复杂度分析

  • 时间复杂度:O(m + n),其中 m 是字符串 ransomNote 的长度,n 是字符串 magazine 的长度,我们只需要遍历两个字符一次即可。
  • 空间复杂度:O(|S|),S是字符集,这道题中 S 为全部小写英语字母,因此∣S∣=26。

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/ransom-note/solution/shu-jin-xin-by-leetcode-solution-ji8a/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论区大佬解法:

梦璃夜·天星

【C++】哈希计数 + 遍历

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int cnt[26]{};
        for(char c: ransomNote) --cnt[c-'a'];
        for(char c: magazine) ++cnt[c-'a'];
        return all_of(cnt, cnt + 26, [](int x){return x >= 0;});
    }
};

根据其做的一些更改(不建议使用系统数组):

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> cnt(26,0);
        for(char c: ransomNote) --cnt[c-'a'];
        for(char c: magazine) ++cnt[c-'a'];
        return all_of(cnt.cbegin(), cnt.cend(), [](int x){return x >= 0;});
    }
};

 可以去复习一下lambda函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值