ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

力扣383-赎金信

力扣383-赎金信

赎金信

题目链接

解题思路

  1. 统计magazine中字符出现的字符,用哈希表保存
  2. 遍历ransomNote,记录其中出现的字符,出现一次,哈希表删除对应的字符
  3. 遍历哈希表,如果有的字符出现的次数为负数,则不能拼凑出目标字符
class Solution {
public:bool canConstruct(string ransomNote, string magazine) {bool res = true;unordered_map<char,int> map;for(int i = 0;i<magazine.length();i++){map[magazine[i]]++;}for(int i = 0;i<ransomNote.length();i++){map[ransomNote[i]]--;}auto iter = map.begin();while(iter != map.end()){if(iter->second < 0){res = false;break;}++iter;}return res;}
};
优雅的写法
class Solution {
public:bool canConstruct(string ransomNote, string magazine) {unordered_map<char,int> hash;for(auto a : magazine) hash[a]++;for(auto b : ransomNote){if(!hash[b]) return false;hash[b]--;}return true;}
};
返回列表