题目描述
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
来源:力扣(LeetCode) 链接:leetcode.cn/problems/ra…
思路分析
- 用map记录magazine中的元素和出现次数。
- 在遍历ransomNote中的每一位字符,在map中查询比较,若相同,则对应value值减一;否则,返回false。
- 代码随想录推荐用数组来做,更快。
代码
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
std::unordered_map<char,int> map;
for(char s:magazine){ //构建map
auto iterator = map.find(s);
if(iterator != map.end()){
iterator->second++;
}else{
map.insert(pair<char,int>(s,1));
}
}
for(char s:ransomNote){
auto iterator = map.find(s);
if(iterator != map.end() && iterator->second > 0){
iterator->second--;
}else{
return false;
}
}
return true;
}
};