Question

Formatted question description: https://leetcode.ca/all/383.html

 383	Ransom Note

 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.

 canConstruct("a", "b") -> false
 canConstruct("aa", "ab") -> false
 canConstruct("aa", "aab") -> true

Algorithm

Hash Map counts the number of characters.

Code

Java

import java.util.HashMap;
import java.util.Map;

public class Ransom_Note {

    class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {

            if (ransomNote == null || magazine == null || ransomNote.length() > magazine.length()) {
                return false;
            }

            int[] arr = new int[26];
            for (int i = 0; i < magazine.length(); i++) {
                arr[magazine.toLowerCase().charAt(i) - 'a']++;
            }
            for (int i = 0; i < ransomNote.length(); i++) {
                if(--arr[ransomNote.toLowerCase().charAt(i)-'a'] < 0) {
                    return false;
                }
            }

            return true;
        }
    }

    class Solution_passed {
        public boolean canConstruct(String ransomNote, String magazine) {
            Map<Character, Integer> magM = new HashMap<>();
            for (char c:magazine.toCharArray()){
                int newCount = magM.getOrDefault(c, 0)+1;
                magM.put(c, newCount);
            }
            for (char c:ransomNote.toCharArray()){
                int newCount = magM.getOrDefault(c,0)-1;
                if (newCount<0)
                    return false;
                magM.put(c, newCount);
            }
            return true;
        }

    }
}

All Problems

All Solutions