Description

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

分析

题目的意思是: 给定连个random字符串和一个magazine字符串,问random可不可以由magazine字符串组成。

  • 如果理解题意了,用一个map就可以搞定了,详情请看代码。

代码

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

参考文献

​[LeetCode] Ransom Note 赎金条​