LeetCode - 242. Valid Anagram
Thoughts:
When anything is about frequency, count, or occurrence, I always think of hash map. I can use an object for storing the frequency of each character in the first String. Then, I can iterate over the second string and decrement the frequency of each character in the object. The time complexity will be O(n).
Code:
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
if (s.length !== t.length) {
return false;
}
const map = {};
for (let char of s) {
map[char] = (map[char] || 0) + 1;
}
for (let char of t) {
if (!map[char]) {
return false;
}
map[char]--;
}
return true;
};
Reference
Copyright © 2024 | All rights reserved.