-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy path0242. Valid Anagram.js
51 lines (44 loc) · 1.04 KB
/
0242. Valid Anagram.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Given two strings s and t , write a function to determine if t is an anagram of s.
//
// Example 1:
//
// Input: s = "anagram", t = "nagaram"
// Output: true
//
// Example 2:
//
// Input: s = "rat", t = "car"
// Output: false
//
// Note:
// You may assume the string contains only lowercase alphabets.
//
// Follow up:
// What if the inputs contain unicode characters? How would you adapt your solution to such case?
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
// 1) Sorting
// Time O(n log n)
// Space O(1). Space depends on the sorting implementation which, usually, costs O(1) auxiliary space if heapsort is used.
const isAnagram1 = (s, t) => {
return s.split('').sort().join('') === t.split('').sort().join('');
};
// 2) Hashmap
// Time O(n)
// Space O(n)
const isAnagram = (s, t) => {
if (s.length !== t.length) return false;
const map = {};
for (const c of s) {
if (map[c] == null) map[c] = 0;
map[c]++;
}
for (const c of t) {
if (map[c] > 0) map[c]--;
else return false;
}
return true;
};