Eagle233-Blog

[Algorithms] LeetCode 383. 赎金信


Categories Algorithms HashTable
Tags

142 Words   |   1 Minutes

来源:代码随想录

LeetCode 383. 赎金信

unordered_map

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<int, int> umap;
        for (int i = 0; i < magazine.size(); i++) {
            umap[magazine[i]]++;
        }
        for (int i = 0; i < ransomNote.size(); i++) {
            umap[ransomNote[i]]--;
        }

        for (auto iter : umap) {
            if (iter.second < 0) {
                return false;
            }
        }

        return true;
    }
};

数组

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> a(26, 0);

        for (int i = 0; i < magazine.size(); i++) {
            a[magazine[i] - 'a']++;
        }

        for (int i = 0; i < ransomNote.size(); i++) {
            a[ransomNote[i] - 'a']--;
        }

        for (int i : a) {
            if (i < 0) {
                return false;
            }
        }

        return true;
    }
};


Page views: Loading...  ·  Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号
Search