242. Valid Anagram
Problem
Tags: Hash Table
, String
, Sorting
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 * 10^4
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?
Code
JS
// 242. Valid Anagram (4/14/53726)
// Runtime: 88 ms (75.26%) Memory: 39.59 MB (93.89%)
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const map = {};
for (let i = 0; i < t.length; i++) map[t[i]] = (map[t[i]] || 0) + 1;
for (let i = 0; i < s.length; i++) {
if (!map[s[i]]) return false;
map[s[i]]--;
}
return true;
}