Created
February 4, 2021 21:00
-
-
Save mustafadalga/c2b0b732edc85577e245aa36a75ae8d4 to your computer and use it in GitHub Desktop.
Given two strings, write a function to determine if the second string is an anagram of the first. An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validAnagram(str1, str2) { | |
if (typeof str1 != "string" || typeof str2 != "string") return false; | |
if (str1.length != str2.length) return false; | |
[str1, str2] = [str1.toLocaleLowerCase(), str2.toLocaleLowerCase()] | |
let frequencyStr1 = {} | |
let frequencyStr2 = {} | |
for (let char of str1) { | |
frequencyStr1[char] = (frequencyStr1[char] || 0) + 1 | |
} | |
for (let char of str2) { | |
frequencyStr2[char] = (frequencyStr2[char] || 0) + 1 | |
} | |
for (let char in frequencyStr1) { | |
if (frequencyStr1[char] != frequencyStr2[char]) { | |
return false | |
} | |
} | |
return true | |
} | |
validAnagram('', ''), // true | |
validAnagram('aaz', 'zza'), // false | |
validAnagram('anagram', 'nagaram'), // true | |
validAnagram("rat", "car"), // false) // false | |
validAnagram('awesome', 'awesom'), // false | |
validAnagram('qwerty', 'qeywrt'), // true | |
validAnagram('texttwisttime', 'timetwisttext') // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment