All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0301_0400.s0383_ransom_note.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0301_0400.s0383_ransom_note;

// #Easy #String #Hash_Table #Counting #Data_Structure_I_Day_6_String
// #2022_07_13_Time_1_ms_(99.97%)_Space_46_MB_(62.86%)

/**
 * 383 - Ransom Note\.
 *
 * Easy
 *
 * Given two stings `ransomNote` and `magazine`, return `true` if `ransomNote` can be constructed from `magazine` and `false` otherwise.
 *
 * Each letter in `magazine` can only be used once in `ransomNote`.
 *
 * **Example 1:**
 *
 * **Input:** ransomNote = "a", magazine = "b"
 *
 * **Output:** false
 *
 * **Example 2:**
 *
 * **Input:** ransomNote = "aa", magazine = "ab"
 *
 * **Output:** false
 *
 * **Example 3:**
 *
 * **Input:** ransomNote = "aa", magazine = "aab"
 *
 * **Output:** true
 *
 * **Constraints:**
 *
 * *   1 <= ransomNote.length, magazine.length <= 105
 * *   `ransomNote` and `magazine` consist of lowercase English letters.
**/
public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] a = new int[26];
        int n = ransomNote.length();
        for (int i = 0; i < n; i++) {
            a[ransomNote.charAt(i) - 97]++;
        }
        for (int i = 0; i < magazine.length() && n != 0; i++) {
            if (a[magazine.charAt(i) - 97] > 0) {
                n--;
                a[magazine.charAt(i) - 97]--;
            }
        }
        return n == 0;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy