NYUer | LeetCode383 Ransom Note

LeetCode383 Ransom Note


Author: Stefan Su
Create time: 2022-10-31 19:27:22
Location: New York City, NY, USA

Description Easy

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
Constrains
  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

Analysis

Use hash array to solve this problem. Define hash_array, and the size of this array is length of 26 letters. Go through magazin, and assign hash_array[ord(_) - ord('a')] += 1 so that it records witch letter appears and how much time it occurs. And then go through ransomNote, hash_array[ord(_) - ord('a')] -= 1. After this operation, if there is value less than 0, it indicates that the time of letter’s occurrence in ransomNote is more than it in magazine, which should return False.

Solution

  • hash array version
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        # use hash array
        hash_array = [0] * 26

        # update hash_array according to each letter in magazine
        for _ in magazine:
            hash_array[ord(_) - ord('a')] += 1
        
        # update hash_array by subtracting 1 at index ord(_) - ord('a')
        for _ in ransomNote:
            hash_array[ord(_) - ord('a')] -= 1

        # go through each in hash_array, if one less than 0, 
        # it means that this letter occurs more times in ransomNote than magazine
        for _ in hash_array:
            if _ < 0:
                return False
        return True
  • more efficient hash array version
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        # use hash array
        hash_array = [0] * 26

        # update hash_array according to each letter in magazine
        for _ in magazine:
            hash_array[ord(_) - ord('a')] += 1

        # more efficient version
        for _ in ransomNote:
            if hash_array[ord(_) - ord('a')] == 0:
                return False
            else:
                hash_array[ord(_) - ord('a')] -= 1
        return True

Hopefully, this blog can inspire you when solving LeetCode383. For any questions, please comment below.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值