Given two strings s and t, return true if t is an anagram of s, and false otherwise.
By | 8 months ago
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
To determine if one string is an anagram of another in JavaScript, you can follow these steps:
- Check if the lengths of both strings are equal. If not, they can't be anagrams.
- Count the frequency of each character in the first string.
- Decrease the frequency of each character encountered in the second string.
- If at any point the frequency becomes negative or after processing the second string, any character's frequency is not zero, the strings are not anagrams.
Here's a JavaScript function that implements this logic:
function isAnagram(s, t) { if (s.length !== t.length) { return false; } const count = {}; // Count the frequency of each character in s for (let i = 0; i < s.length; i++) { const char = s[i]; count[char] = (count[char] || 0) + 1; } // Decrease the frequency for each character in t for (let i = 0; i < t.length; i++) { const char = t[i]; if (!count[char]) { return false; // char not found or frequency is 0, not an anagram } count[char]--; } return true; } // Test the function console.log(isAnagram("anagram", "nagaram")); // Output: true console.log(isAnagram("rat", "car")); // Output: false
This function first ensures the strings are of equal length. Then, it uses a `count` object to track the number of occurrences of each character in the first string and decreases the corresponding count for each character in the second string. If a character in the second string doesn't exist in the `count` object or its count drops below zero, the function returns false, indicating the strings are not anagrams. If all characters match appropriately, it returns true.