-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisAnagram.js
37 lines (26 loc) · 817 Bytes
/
isAnagram.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
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
*/
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const map = new Map();
// Count the occurrences of each character in string 's'
for (const char of s) {
map.set(char, (map.get(char) || 0) + 1);
}
// Validate the occurrences of each character in string 't'
for (const char of t) {
if (!map.has(char) || map.get(char) === 0) {
return false;
}
map.set(char, map.get(char) - 1);
}
return true;
}