给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> hash(26,0);
if (ransomNote.size() > magazine.size()) {
return false;
}
for(auto &it:magazine){
hash[it-'a']++;
}
for(auto &it:ransomNote){
hash[it-'a']--;
if(hash[it-'a']<0)
return false;
}
return true;
}
};
通过数组模拟哈希表,先遍历后串,通过-'a'对串中字符计数,再遍历前串,相同时减去对应key的计数,若小于0则说明前串无法覆盖后串。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ransom-note
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。