LeetCode 0383 Ransom Note【赎金信,哈希】

本文介绍了一种解决勒索信问题的算法,通过使用哈希表记录杂志字符串中每个字符的出现次数,检查是否能完全构造出勒索信字符串。文章详细解释了算法思路与实现过程,并提供了具体代码示例。

题目链接 383. Ransom Note |

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.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:

  • You may assume that both strings contain only lowercase letters.

题意

  • 看字符串ransomNote能否被字符串 magazine 构造出来,magazine中的每个字符只允许被使用一次

  • 字符串中仅包含小写字母

思路1

  • 使用一个哈希表记录下 magazine 中每个字符出现次数
  • 遍历 ransomNote 中每个字符,每次将哈希表中的次数减1,若出现减完之后的结果小于0,则显然不符,否则可以。

代码1

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int cnt[26] = {0};
        for(const auto &it : magazine)
            cnt[it - 'a']++;
        bool ans = true;
        for(const auto &it : ransomNote)
        {
            if(cnt[it - 'a'])
                cnt[it - 'a']--;
            else
            {
                ans = false;
                break;
            }
        }
        return ans;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值