森田賢二のleetCodeの使い方、解説、解答を毎日更新しているキャラクター

[leetcode]問題解答と解説。389. Find the Difference [JavaScript]

[leetcode]問題解答と解説。389. Find the Difference [JavaScript]

皆さんleetCode好きですよね。私も好きです。
なかなかやる機会がないのですよね。
leetCodeの使い方や解説ではなく実際に問題を解決するために何をしたか
をメモ書きして行きます

私はある決意をして今挑んでいます。
モチベーションを保つためだけにこれをやっています。

では今日のleetCode。
【389. Find the Difference】の解決策と方法。自分がまず挑戦して
やったことをさらけ出します。

※下にある自分のコードは自分で設けた制限時間内に書けたところまです。

これは
「私は年末までこれを続けたらどんなleetCoderになるか」のシリーズ。
実験的ブログ更新です。

森田賢二のleetCode
森田賢二のleetCode

[leetcode] 389. Find the Difference ルール

You are given two strings s and t.

String t is generated by random shuffling string s and then add one more letter at a random position.

Return the letter that was added to t.

Example 1:

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y"
Output: "y"

違うものを返せというもの。
注意しなくてはいけないのは文字は何回も出現してきて出現回数も同じだが
一つだけ出現回数が違う文字がある

exampleは実際の問題ページを見てください

[leetcode] 389. Find the Difference 問題ページ

389. Find the Difference

[leetcode] 389. Find the Difference

my code is not completed

/**
 * @param {string} s
 * @param {string} t
 * @return {character}
 */
var findTheDifference = function(s, t) {
    const map = [...s].reduce((a, c) => {
        if(a.has(c)){
            a.set(c, a.get(c) + 1)
            return a
        }
     return a.set(c, 0)
    }, new Map())
    const map2 = [...t].reduce((a, c) => {
        if(a.has(c)){
            a.set(c, a.get(c) + 1)
            return a
        }
     return a.set(c, 0)
    }, new Map())
    for(let m of map2){
        if(map.has(m[0])){
            if(map.get(m[0]) === map2.get(m[0])){
                continue;
            }
            return m[0]
        }
        return m[0]
    }
    return "" // TODO
};

[leetcode] 389. Find the Difference。discussの中の一つの解答例

数ある中からJavaScriptのもので、理解しやすい解説をピックアップしました。
discussから見ればさらにもっと違う方法で真似したくなるものがあるかもしれない

[JavaScriptでfilterされている、discussはこちらから]()

気に入った解答1

var findTheDifference = function(s, t) {
    const hashmap = {};
    for (let i = 0; i < s.length; i++) {
        if (!hashmap[s[i]]) hashmap[s[i]] = [];

        hashmap[s[i]].push(i);
    }

    for (let i = 0; i < t.length; i++) {
        if (!hashmap[t[i]]?.length) return t[i];

        hashmap[t[i]].pop();
    }
};

replace

var findTheDifference = function(s, t) {
    for (let letter of s)
        t = t.replace(letter, '');
    return t;
};

[leetcode] 389. Find the Difference をやってみて感想

  • 自分のコードのパフォーマンスの悪さ

カテゴリー leetCode