383. Ransom Note (Easy)

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

Solutions

class Solution {

    public boolean canConstruct(String ransomNote, String magazine) {

        // Following statement is crucial
        if (ransomNote == null || ransomNote.length() == 0) {
            return true;
        }

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

        Map<Character, Integer> occurrence = new HashMap<>();

        for (int i = 0; i < magazine.length(); i++) {
            Character c = magazine.charAt(i);
            if (!occurrence.containsKey(c)) {
                occurrence.put(c, 0);
            }

            occurrence.put(c, occurrence.get(c) + 1);
        }

        for (int i = 0; i < ransomNote.length(); i++) {
            Character c = ransomNote.charAt(i);
            if (!occurrence.keySet().contains(c)) {
                return false;
            }

            if (occurrence.get(c) == 0) {
                return false;
            }

            occurrence.put(c, occurrence.get(c) - 1);
        }

        return true;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 00:26:46

results matching ""

    No results matching ""