LeetCode Ransom Note

LeetCode 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字符串。简单题,直接hash解决,使用的是unordered_map,完整代码如下: [cpp] class Solution { public: bool canConstruct(string ransomNote, string magazine) { unordered_map<char, int> hash; for (int i = 0; i < magazine.size(); i++) { hash[magazine[i]]++; } for (int i = 0; i < ransomNote.size(); i++) { hash[ransomNote[i]]–; if (hash[ransomNote[i]] < 0)return false; } return true; } }; [/cpp] 本代码提交AC,用时76MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *