(Js) Leetcode 383. Ransom letter

topic:

Given a ransom letter (ransom) string and a magazine (magazine) string, determine whether the first string ransom can be composed of the characters in the second string magazines. If it can be formed, return true; otherwise, return false.

(Title description: In order not to expose the handwriting of the ransom letter, search for the required letters from the magazine and form words to express the meaning. Each character in the magazine string can only be used once in the ransom letter string.)

note:

You can assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

Ideas:

1. Count the number of occurrences of each character in the magazine string and store it in the map

2. Match each character of the ransom letter string with map,

    1) If the value is 0, return false

    2) Otherwise, continue to match the next character

3. Return true

Code:

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    let map = new Map(), count = 0;
    for(let i = 0; i < magazine.length; i++) {
        count = map.get(magazine[i]) || 0;
        map.set(magazine[i], ++count);
    }
    for(let i = 0; i < ransomNote.length; i++) {
        count = map.get(ransomNote[i]) || 0;
        if(count) {
            map.set(ransomNote[i], --count);
        } else {
            return false;
        }
    }
    return true;
};

operation result:

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113005857