LeetCode383. Ransom Note

文章讲述了如何使用哈希表(数组模拟)解决给定两个字符串(ransomNote和magazine)的问题,判断ransomNote是否能通过magazine中的字母唯一构造。通过统计magazine中每个字符出现的次数,然后逐个检查ransomNote中字符是否可用,若发现某个字符不足则返回false,否则返回true。
摘要由CSDN通过智能技术生成

一、题目

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

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:

1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine consist of lowercase English letters.

二、题解

使用数组模拟哈希表解决

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int n1 = ransomNote.length();
        int n2 = magazine.length();
        vector<int> chars(26,0);
        for(int i = 0;i < n2;i++){
            chars[magazine[i] - 'a']++; 
        }
        for(int i = 0;i < n1;i++){
            if(chars[ransomNote[i] - 'a'] == 0) return false;
            chars[ransomNote[i] - 'a']--;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值