STRING ANAGRAM JAVASCRIPT
Tue Dec 20 2022 09:12:36 GMT+0000 (Coordinated Universal Time)
Saved by
@YaseenBhojani
#javascript
// STRING ANAGRAM
// "hello" -> "llheo"
// condition
// length check (for both string)
// String "hello"
// { h: 1, e: 1, l: 2, o: 1}
const isAnagram = (str1, str2) => {
if (str1.length !== str2.length) {
return false;
}
let counter = {};
for (let letter of str1) {
counter[letter] = (counter[letter] || 0) + 1;
}
for (let letter of str2) {
if (!counter[letter]) {
return false;
}
counter[letter] -= 1;
}
return true;
};
const result = isAnagram("hello", "llheo");
console.log(result); // true
content_copyCOPY
Comments