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

Thought

Since we can assume that both strings contain only lowercase letters, just prepare an array mapping to a-z and count the number of times for each one in magazine. For example, given the magazine="aab",

index        0     1     2            24    25
chars     |  a  |  b  |  c  |  ...  |  y  |  z  |
count        2     1     0     ...     0     0

after the preparation of magazine, traverse the chars in ransome note and consume the count in the array.

Solution

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        // why 26? assume that both strings contain only lowercase letters
        int[] alphabet = new int[26];
        // ASCII value for 'a' is 97, then count for each character in magazine
        for (int i = 0; i < magazine.length(); i++)
            alphabet[magazine.charAt(i) - 97]++;
        // consume the array and check inventory
        for (int i = 0; i < ransomNote.length(); i++)
            if (--alphabet[ransomNote.charAt(i) - 97] < 0) return false;

        return true;
    }
}

results matching ""

    No results matching ""