LoginSignup
0
0

More than 1 year has passed since last update.

LeetCode easy: 383. Ransom Note

Last updated at Posted at 2022-07-20

LeetCodeを解いているので記録しています。

解いた問題

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

処理の流れ

magazineの中身を一回しか使えないのに注意
シンプルに考えると、ransomNoteの文字列をforループで回してmagazineの文字列を検索。
なければその場でFalseを返す。
あればmagazineの中の文字を削除してループに戻る。
最後までループが完了すればtrue

調べたこと

文字列検索。含まれていない時は-1が返る。

指定した文字削除

The original string is left unchanged.
非破壊。str.replace()しても元の文字(str)は変わらない!

最初に書いたコード

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    for (var i = 0; i < ransomNote.length; i++) {
        if (magazine.indexOf(ransomNote[i]) === -1) {
            return false
        } else {
            // if found  
            // delete a letter
            magazine = magazine.replace(ransomNote[i], '')
        }
    }
    return true
};

Runtime: 103 ms, faster than 81.57% of JavaScript online submissions for Ransom Note.
Memory Usage: 49.3 MB, less than 10.08% of JavaScript online submissions for Ransom Note.

解いた後に

動画はないのでDiscussのページを見てみる。
投票率の高いJavascriptのコード
https://leetcode.com/problems/ransom-note/discuss/385887/Javascript-solution

var canConstruct = function(ransomNote, magazine) {
    const map = {};
    for(let letter of magazine) {
        if (!map[letter]) {
            map[letter] = 0;
        }
        map[letter]++;
    }
    
    for(let letter of ransomNote) {
        if(!map[letter]) {
            return false;
        } 
        map[letter]--;
    }
    return true;
};

まずmagazineをforloopで回して、
mapというオブジェクトに文字と現れる回数の辞書をつくる。
magazine = "abbcccddddeeeee" のとき
map = { a: 1, b: 2, c: 3, d: 4, e: 5 }

同様にransomNoteをforloopで回して、
mapに対象の文字列が現れるたびに文字を減らす。
無くなった時点でfalseを返し最後まで行けた場合はtrueを返す。
大体やっていることは同じ。
ちなみに速度は

Runtime: 133 ms, faster than 49.25% of JavaScript online submissions for Ransom Note.
Memory Usage: 44.8 MB, less than 60.46% of JavaScript online submissions for Ransom Note.

ちなみにPythonでは
https://leetcode.com/problems/ransom-note/discuss/1346131/Easiest-python-solution-faster-than-95

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0