valid anagram
Link : https://neetcode.io/problems/is-anagram
solution 1
function isAnagram_01(s, t) {
const x = {};
const y = {};
if (s.length !== t.length) {
return false;
}
for (let i = 0; i < s.length; i++) {
// if (x.hasOwnProperty(s[i])) {
// x[s[i]] = ++x[s[i]];
// } else {
// x[s[i]] = 1;
// }
// if (y.hasOwnProperty(t[i])) {
// y[t[i]] = ++y[t[i]];
// } else {
// y[t[i]] = 1;
// }
x[s[i]] = 1 + (x[s[i]] ?? 0);
y[t[i]] = 1 + (y[t[i]] ?? 0);
}
for (const property in x) {
if (x[property] !== y[property]) {
return false;
}
}
return true;
}
solution 2
var isAnagram_02 = function (s, t) {
if (s.length !== t.length) {
return false;
}
const lookup = {};
for (let i = 0; i < s.length; i++) {
if (lookup.hasOwnProperty(s[i])) {
lookup[s[i]] = ++lookup[s[i]];
} else {
lookup[s[i]] = 1;
}
}
for (let i = 0; i < t.length; i++) {
if (lookup.hasOwnProperty(t[i])) {
lookup[t[i]] = --lookup[t[i]];
} else {
lookup[t[i]] = 1;
}
}
for (const property in lookup) {
if (lookup[property] > 0) {
return false;
}
}
return true;
};