Interview 150

Ransom Note

Problem
LC 383
File
interview150_LC383RansomNote.java
Path
pkg5leetcode/interview150/interview150_LC383RansomNote.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC383RansomNote.java
Approach
Count magazine chars; decrement for ransomNote.
Complexity
Time O(m+n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC383RansomNote.java
1package pkg5leetcode.interview150;2 3/*4 * Ransom Note | LC 3835 * APPROACH: Count magazine chars; decrement for ransomNote.6 * COMPLEXITY: Time O(m+n), Space O(1)7 */8public class interview150_LC383RansomNote {9    static boolean canConstruct(String ransomNote, String magazine) {10        int[] cnt = new int[26];11        for (char c : magazine.toCharArray()) cnt[c - 'a']++;12        for (char c : ransomNote.toCharArray()) {13            if (--cnt[c - 'a'] < 0) return false;14        }15        return true;16    }17 18    public static void main(String[] args) {19        check(!canConstruct("a", "b"), "case1");20        check(!canConstruct("aa", "ab"), "case2");21        check(canConstruct("aa", "aab"), "case3");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}