给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
建立一个哈希表,索引为字母,值为字母出现的次数。
class Solution {
public:
bool canConstruct(const string& ransomNote, const string& magazine) {
vector<size_t> letter_times(26);
for (const char& letter : magazine) {
size_t index = letter - 'a';
letter_times[index]++;
}
for (const char& letter : ransomNote) {
size_t index = letter - 'a';
if (letter_times[index] <= 0) {
return false;
} else {
letter_times[index]--;
}
}
return true;
}
};
时间复杂度为O(m+n),空间复杂度为O(1)。