242. Valid Anagram
Valid Anagram
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.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104
s
andt
consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if(s.length != t.length) return false;
var s = s.split("").sort().join("");
var t = t.split("").sort().join("");
return s == t;
};
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if(s.length !== t.length) return false;
let map = {};
for(let i=0; i<s.length; i++){
if(!map[s[i]]) map[s[i]] = 0;
if(!map[t[i]]) map[t[i]] = 0;
map[s[i]]++;
map[t[i]]--;
}
for(let key in map){
if(map[key] != 0) return false
}
return true;
};
Conclusion
That’s all folks! In this post, we solved LeetCode problem #242. Valid Anagram
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment