美文网首页
383. 赎金信

383. 赎金信

作者: KaMu1 | 来源:发表于2019-10-15 16:12 被阅读0次

解题思路

统计magzine字符串中每一个字符串的出现次数,再遍历ransom中每一字母。

STL实现

unorder_map直接利用[]给不存在的key-value赋值是可行的
不存在的key对应的value++先赋值默认值

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char,int> mag;
        
        for(auto iter = magazine.begin();iter!=magazine.end();iter++) {
            mag[*iter] += 1;
        }
        
        for(auto iter = ransomNote.begin();iter!=ransomNote.end();iter++) {
            mag[*iter] -= 1;
            if(mag[*iter]<0)
                return false;
        }
        return true;
    }
};

直接利用简单的hash

本题中只有小写字母,直接hash更加方便
使用STL迭代器在某些情况下会造成性能浪费
magazine[i]判断是否遍历完全

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

相关文章

  • Leetcode-383 赎金信

    383. 赎金信[https://leetcode-cn.com/problems/ransom-note/] 解...

  • 383. 赎金信

    解题思路 统计magzine字符串中每一个字符串的出现次数,再遍历ransom中每一字母。 STL实现 unord...

  • 383. 赎金信

    题目描述:给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ranso...

  • 「算法」383. 赎金信。

    为了不在赎金信中暴露字迹,从杂志上搜索各个需要的字母,组成单词来表达意思。给你一个赎金信 (ransomNote)...

  • LeetCode-python 383.赎金信

    题目链接难度:简单 类型: 集合 给定一个赎金信 (ransom) 字符串和一个杂志(maga...

  • 2022-02-28 「383. 赎金信」

    不知道今天的简单题够判多少年:https://leetcode-cn.com/problems/ransom-no...

  • 赎金信

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/ransom...

  • Leetcode PHP题解--D102 383. Ransom

    D102 383. Ransom Note 题目链接 383. Ransom Note 题目分析 给定一个字符串,...

  • leetcode算法-赎金信

    赎金信 https://github.com/wangeastsea/algorithm-leetCode/tre...

  • 383-赎金信

    赎金信 题目 给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ran...

网友评论

      本文标题:383. 赎金信

      本文链接:https://www.haomeiwen.com/subject/tnusmctx.html