383. ransom note

https://leetcode.com/problems/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


  • code
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> count = new HashMap<>();
        for (Character c: magazine.toCharArray()){
            count.put(c, count.getOrDefault(c, 0) + 1);
        }
        for (Character c: ransomNote.toCharArray()){
            count.put(c, count.getOrDefault(c, 0) - 1);
            if (count.getOrDefault(c, 0) < 0) return false;
        }
        return true;
    }
}
  • code
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] count = new int[26];
        
        for (char c: magazine.toCharArray()){
            count[c - 'a']++;
        }
        
        for (char c: ransomNote.toCharArray()){
            count[c - 'a']--;
            if (count[c - 'a'] < 0) return false;
        }
        return true;
    }
}
  • code
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        c1, c2 = collections.Counter(ransomNote), collections.Counter(magazine)
        return all(k in c2 and c2[k]>=c1[k] for k in c1)

  • code
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        return all(ransomNote.count(c)<=magazine.count(c) for c in set(ransomNote))