Ransom Note LeetCode | Ransom LeetCode Solution Java | LeetCode 383

preview_player
Показать описание
Ransom Note LeetCode Solution Multiple Approaches using Java Code.

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.

Note:
You may assume that both strings contain only lowercase letters.

For Example -

Example 1-

ransomNote = "a" magazine = "b"

canConstruct("a", "b") : false

Example 2-

ransomNote = "aa" magazine = "ab"

canConstruct("aa", "ab") : false

Example 3-

ransomNote = "aa" magazine = "aab"

canConstruct("aa", "aab") : true

Рекомендации по теме
Комментарии
Автор

perfect explanation, thank you so much!!

kunalkheeva
Автор

Good one! Please try to include the leetcode editor in your next videos. Just to show accepted time and other details. It gives us a basic insight how optimized solution improved the code drastically :)

pahehepaa
Автор

I already solved the problem and is looking for more optimised way of solving. As of now my runtime is 76ms which only beats 26% of Python3 code submissions. Can anyone provide with the more optimized way? My Python3 code using array is:

class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
A = [0]*26
for i in magazine:
A[ord(i) - 97] += 1
for i in ransomNote:
if A[ord(i) - 97] >= 1:
A[ord(i) - 97] -= 1
else:
return False
return True

SaurabhSingh-yolz
Автор

Hi, good initiative.
I have solved the problem with the first approach. However, when I am submitting my solution it is saying 97 out of 127 test case passed. Which means still 30 case is failed. Did you get the same result after submission?

AbhishekPandey-yipf
visit shbcf.ru