383. Ransom Note
https://leetcode.com/problems/ransom-note/description/?envType=study-plan-v2&envId=top-interview-150
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: falseExample 2:
Input: ransomNote = "aa", magazine = "ab"
Output: falseExample 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105ransomNoteandmagazineconsist of lowercase English letters.
Solution:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() > magazine.length()) return false;
int[] alphabets_counter = new int[26];
for (char c : magazine.toCharArray())
alphabets_counter[c-'a']++;
for (char c : ransomNote.toCharArray()){
if (alphabets_counter[c-'a'] == 0) return false;
alphabets_counter[c-'a']--;
}
return true;
}
}Last updated
Was this helpful?