-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path242_Valid_Anagram.js
More file actions
55 lines (48 loc) · 1.26 KB
/
Copy path242_Valid_Anagram.js
File metadata and controls
55 lines (48 loc) · 1.26 KB
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
52
53
54
55
/*
242. Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
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?
*/
const expect = require('expect');
describe('242 Valid Anagram', () => {
it('returns it is a valid anagram', () => {
//arrange
const input = ['anagram', 'nagaram'];
const expected = true;
//act
const actual = isAnagram(...input);
//assert
expect(actual).toBe(expected);
});
it('returns it is NOT a valid anagram', () => {
//arrange
const input = ['rat', 'car'];
const expected = false;
//act
const actual = isAnagram(...input);
//assert
expect(actual).toBe(expected);
});
});
const isAnagram = (s, t) => {
if (s.length !== t.length) return false;
const hashS = {};
const hashT = {};
for (let index = 0; index < s.length; index++) {
incrementHash(hashS, s[index]);
incrementHash(hashT, t[index]);
}
for (const [key, value] of Object.entries(hashS)) {
if (value !== hashT[key]) return false;
}
return true;
};
const incrementHash = (hash, key) => {
if (!hash[key]) hash[key] = 1;
else {
hash[key]++;
}
};