Easy difficulty · Question · Topics: string, hashmap, hash-table
Given two strings s and t, determine whether they are anagrams of each other.
Two strings are anagrams if they contain exactly the same characters, with each character appearing the same number of times, regardless of the order in which the characters appear.
Return true if the strings are anagrams; otherwise, return false.
Example 1
Input:
s = "racecar"
t = "carrace"
Output:
true
Explanation: Both strings contain the same characters with identical frequencies, so they are anagrams.
Example 2
Input:
s = "jar"
t = "jam"
Output:
false
Explanation: The strings contain different characters: appears in , while appears in .
rsmtExample 3
Input:
s = "x"
t = "x"
Output:
true
Explanation: Both strings contain the same character with the same frequency.
Use a character frequency counter to compare the occurrences of each character in both strings.
false immediately because they cannot be anagrams.26 to track the occurrences of lowercase English letters.s and increment the frequency count for each character.t and decrement the frequency count for each character.false because t contains a character more times than s.true.class Solution {
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
isAnagram(s, t) {
if(s.length !== t.length) return false;
let mapper = [];
const charValofA = "a".charCodeAt(0);
for(var k = 0;k<=26;k++) mapper[k] = 0;
for(var i =0;i<t.length;i++){
mapper[s.charCodeAt(i)-charValofA] = mapper[s.charCodeAt(i)-charValofA]-1;
mapper[t.charCodeAt(i)-charValofA] = mapper[t.charCodeAt(i)-charValofA]+1;
}
for(var i =0;i<26;i++){
if(mapper[i] !== 0) return false;
}
return true;
}
}