Leetcode problem 42 - 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
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
if (s.length !== t.length) {
return false;
}
s = s.split("").sort().join("");
t = t.split("").sort().join("");
return s === t;
};
It checks if the lengths of the two strings are different, and if so, returns false
immediately.
It splits both strings into arrays of characters using split("")
.
It sorts the character arrays using the sort()
method, which arranges the characters in ascending order.
It joins the sorted character arrays back into strings using join("")
.
Finally, it compares the sorted strings to check if they are equal, and if they are, it returns true
, indicating that the strings are anagrams; otherwise, it returns false
.
Leave a comment