242. Valid Anagram
Leetcode
https://leetcode.com/problems/valid-anagram/
題目
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
è§£ç”
方法一
var isAnagram = function(s, t) {
if(s.length != t.length) return false;
s = s.split("").sort().join("");
t = t.split("").sort().join("");
return s == t;
};Runtime: 188 ms, faster than 9.30% of JavaScript online submissions for Valid Anagram.
Memory Usage: 44.7 MB, less than 22.52% of JavaScript online submissions for Valid Anagram.
方法二
var isAnagram = function(s, t) {
if(s.length != t.length) return false;
const hash1 = {};
const hash2 = {};
for(let i=0; i<s.length; i++) {
const value1 = s[i];
if(hash1[value1]) hash1[value1]++;
else hash1[value1] = 1;
const value2 = t[i];
if(hash2[value2]) hash2[value2]++;
else hash2[value2] = 1;
}
for(let key of Object.keys(hash1)) {
if(hash1[key] !== hash2[key]) return false;
}
return true;
};Runtime: 117 ms, faster than 41.56% of JavaScript online submissions for Valid Anagram.
Memory Usage: 39.6 MB, less than 97.20% of JavaScript online submissions for Valid Anagram.
測資
let s = "rat", t = "car";
s = "anagram", t = "nagaram";
console.log(isAnagram(s, t))Last updated
Was this helpful?