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就可以搞定了,详情请看代码。
C++实现
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;
}
};
Python实现
思路就是用hash map实现,一个一个的比对。
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
m = defaultdict(int)
for ch in magazine:
m[ch]+=1
for ch in ransomNote:
m[ch]-=1
if m[ch]<0:
return False
return True