383. Ransom Note

Leetcode

https://leetcode.com/problems/ransom-note/

題目

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.

解答

  • 方法一

var canConstruct = function(ransomNote, magazine) {
    for(let i=0; i<ransomNote.length; i++) {
        const char = ransomNote[i];
        const index = magazine.indexOf(char);
        if(~index) magazine = magazine.slice(0, index) + magazine.slice(index+1);
        else return false;
    }
    return true;
};

Runtime: 84 ms, faster than 95.76% of JavaScript online submissions for Ransom Note.

Memory Usage: 46 MB, less than 8.92% of JavaScript online submissions for Ransom Note.

測資

let ransomNote = "aa", magazine = "ab";
ransomNote = "aa", magazine = "aab";

console.log(canConstruct(ransomNote, magazine));

Last updated

Was this helpful?