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.

测试用例

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


Input: s = "a", t = "aa"
Output: "a"

题解

首先依旧是收集对象字符串的字符,再去目标字符串进行比对。

var findTheDifference = function(s, t) {
    let _target = {};
    for(let c of s) {
        _target[c] = _target[c] ? _target[c] + 1 : 1;
    }
    for(let c of t) {
        if(!_target[c]) return c;
        else _target[c]--;
    }
};

结果

Accepted

54/54 cases passed (114 ms)

Your runtime beats 15.8 % of javascript submissions

Your memory usage beats 29.98 % of javascript submissions (41 MB)


文章作者: 阿汪同学
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 阿汪同学 !
评论
  目录