力扣383-赎金信

赎金信

题目链接

解题思路

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

你可能感兴趣的:(算法-每日一练,leetcode,哈希算法,算法)