title: 242.valid-anagram
date: 2021-10-13 16:31:14
tags:
- LeeCode
categories:
- LeeCode
hidden: true
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
有效的字母异位词。
// example 1
Input: s = "anagram", t = "nagaram"
Output: true
// example 2
Input: s = "rat", t = "car"
Output: false
对字符串的字符进行收集并比较。
var isAnagram = function(s, t) {
if(s.length !== t.length) return false;
let s_r = null, t_r = null;
s_r = getChars(s);
t_r = getChars(t);
if(Object.keys(s_r).length !== Object.keys(t_r).length) return false;
let flag = true;
Object.keys(s_r).forEach(key => {
if(s_r[key] !== t_r[key]) {
flag = false;
return flag;
}
})
return flag;
function getChars(s) {
let result = {};
for (let i = 0; i < s.length; i++) {
result[s[i]] ? result[s[i]]++ : (result[s[i]] = 1);
}
// console.log(result);
return result;
}
};
Accepted
35/35 cases passed (99 ms)
Your runtime beats 60.14 % of javascript submissions
Your memory usage beats 66.11 % of javascript submissions (41 MB)