一、问题描述
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
二、思路
给定两个字符串,从其中一个中如果能够找到另一个字符串,返回真,否则返回假。
三、代码
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
if(ransomNote.size() > magazine.size()) return false;
int hash1[256] = {0},hash2[256] = {0};
for(int i = 0; i < ransomNote.size();++i)
hash1[ransomNote[i]]++;
for(int i = 0; i < magazine.size();++i)
hash2[magazine[i]]++;
for(int i = 0; i < 256; ++i){
if(hash1[i] > hash2[i]) return false;
}
return true;
}
};