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

 


本题,实际上是确定ransomNote中出现过的字符是否全部能在magzine中找到。
对于字符串类的题目,我们要时刻牢记一个重要的性质,那就是字符char的编码是和一个整数int一一对应的,在这种情况下可以十分方便地使用hash, map, set等容器,尤其是hash算法,应用十分广泛
本题中,可以使用一个unordered_map<char ,int>,key表示字符,int表示字符key在magzine中出现的次数,因此算法的空间复杂度为O(n),时间复杂度为O(m+n)。
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        if (ransomNote.empty())
            return true;
        if (magazine.empty())
            return false;
        
        unordered_map<char,  int> container;
        for (auto ch : magazine)
            ++(container[ch]);
            
        for (auto ch : ransomNote) {
            if (container[ch] == 0)
                return false;
            else
                --(container[ch]);
        }
        
        return true;
    }
};

 



posted @ 2017-06-12 16:12  NaiveCoder  阅读(171)  评论(0)    收藏  举报