Anagram of two strings means that contains the same characters and the repeating characters are same in the two strings but order of the characters may be different.
Example- "blog" and "logb" ; this two strings are Anagram.
Code in JavaScript :
//Check two strings are anagram or not
//input string : 'hello' and 'llheo'
//first check the length.
//count the alphabate like this {h:1,e:1,l:2,o:1}
//check the each alphabate and decrease by the value by 1
//IF ALL VALUES ARE ZERO THEN ANAGRAM IS TRUE, otherwise false
function isAnagram(string1,string2){
if(string1.length!==string2.length){
return false;
}
let counter={}
for(let letter of string1){
counter[letter]=(counter[letter] || 0) + 1;
}
console.log(counter);
for(let items of string2){
if(!counter[items]){
return false;
}
counter[items]-=1
}
return true;
}
const check=isAnagram('Anagram','gramnAa')
console.log(check);
________________________________________________________________________
Output:
{ A: 1, n: 1, a: 2, g: 1, r: 1, m: 1 }
true
Comments
Post a Comment