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.

猜你喜欢

转载自blog.csdn.net/Moses_SU/article/details/127626677
今日推荐