版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83092415
题目:
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
解释:
数出现的次数即可。
python代码:
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
if ransomNote=="":
return True
for note in set(ransomNote):
if ransomNote.count(note)>magazine.count(note):
return False
return True
c++代码:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
set<char> _set(ransomNote.begin(),ransomNote.end());
for(auto letter:_set)
{
if(count(ransomNote.begin(),ransomNote.end(),letter)>count(magazine.begin(),magazine.end(),letter))
return false;
}
return true;
}
};
总结:
注意stl很多函数传入的都是.begin()
,.end()
。