-
Notifications
You must be signed in to change notification settings - Fork 344
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
找不同-389 #109
Comments
用ES6 Map替换了一下,更方便看。^ ^ LC能跑进80ms
|
似乎可以简化点写法呢: var findTheDifference = function (s, t) {
const sMap = new Map();
for (const c of s) {
sMap.set(c, (sMap.get(c) || 0) + 1);
}
const tMap = new Map();
for (const c of t) {
tMap.set(c, (tMap.get(c) || 0) + 1);
}
// 遍历 tMap,根据两者数量是否一致确定
for (const [key, value] of tMap) {
if (sMap.get(key) !== value) {
return key;
}
}
}; |
利用 ascii 码的计算差值再转换也比上面会更快些: var findTheDifference = function (s, t) {
let sum = 0;
for (const c of t) {
sum += c.charCodeAt();
}
for (const c of s) {
sum -= c.charCodeAt();
}
return String.fromCharCode(sum);
}; |
直接用一个哈希表即可:
|
function fn(s: string, t: string) {
const sArr = s.split('')
const tArr = t.split('')
for(let i = 0; i < sArr.length; i ++) {
const char = sArr[i]
const index = tArr.findIndex(item => item === char)
tArr.splice(index, 1)
}
return tArr[0]
} |
邮件已收到,祝一切安好~
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
查找 map
分别为
s
和t
记录一个字符出现数量的 map,然后遍历长度更长的那个字符串的 map,如果发现某个 key 在另一个 map 中没有出现,那么多出来的就是那个 key 的字符。位运算
利用
^
异或运算,不断的异或字符的charCode
值,相同的值都会消除为 0,最后剩下的就是多出来的字符的charCode
值。The text was updated successfully, but these errors were encountered: