Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active February 25, 2021 05:35
Show Gist options
  • Save lienista/d7c9d2636d8073420639bcdd45e5ccce to your computer and use it in GitHub Desktop.
Save lienista/d7c9d2636d8073420639bcdd45e5ccce to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) Leetcode 242. Valid Anagram - Given two strings s and t , write a function to determine if t is an anagram of s.
const isAnagram => (s, t) {
var lens = s.length,
lent = t.length;
if(lens !== lent) return false;
if(typeof s !== 'string' || typeof t !== 'string') return false;
if(lens === 0 && lent === 0) return true;
var charmap = {};
for(let i=0; i<lens; i++){
charmap[s[i]] = charmap[s[i]] ? charmap[s[i]]+1: 1;
}
for(let j=0; j<lent; j++){
if(charmap[t[j]]) charmap[t[j]]--;
else return false;
}
var sum = Object.values(charmap).reduce(function(accumulator, element){
return accumulator + element;
});
if(sum === 0) return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment