This content originally appeared on DEV Community and was authored by Stylus07
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
var isAnagram = function (s, t) {
if (s.length !== t.length) {
return false;
}
let countS = new Map();
let countT = new Map();
for (let start = 0; start < s.length; start++) {
countS.set(s[start], 1 + (countS.get(s[start]) ? countS.get(s[start]) : 0));
countT.set(t[start], 1 + (countT.get(t[start]) ? countT.get(t[start]) : 0));
}
for (const [key, value] of countS) {
if (countS.get(key) !== countT.get(key)) {
return false;
}
}
return true;
}
Time Complexity : O(n)
Space Complexity : O(s+t)
This content originally appeared on DEV Community and was authored by Stylus07
Stylus07 | Sciencx (2022-04-11T03:10:33+00:00) Valid Anagram. Retrieved from https://www.scien.cx/2022/04/11/valid-anagram/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.