[leetcode]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

分析:

判断magazine中字符串能否从ransomNote字符串中获得。先用哈希表来统计magazine中每个字符的个数,再判断ransomNote相应字符的个数是否相等即可。

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char , int>m;
        for(char c : magazine)
            m[c]++;
        for(char c : ransomNote)
        {
            m[c]--;
            if(m[c] < 0)
                return false;
        }
        return true;        
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/85231488
今日推荐