-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathproblem-one.js
More file actions
63 lines (55 loc) · 1.34 KB
/
problem-one.js
File metadata and controls
63 lines (55 loc) · 1.34 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
56
57
58
59
60
61
62
63
// did this problem on leetcode: https://leetcode.com/problems/valid-anagram/
// initial solution:
const isAnagram = function (s, t) {
const sDictionary = {}
const tDictionary = {}
for (const letter of s) {
if (!sDictionary[letter]) {
sDictionary[letter] = 1
} else {
sDictionary[letter]++
}
}
for (const letter of t) {
if (!tDictionary[letter]) {
tDictionary[letter] = 1
} else {
tDictionary[letter]++
}
}
for (const letter of s) {
if (sDictionary[letter] !== tDictionary[letter]) {
return false
}
}
for (const letter of t) {
if (tDictionary[letter] !== sDictionary[letter]) {
return false
}
}
return true
}
// second attempt after looking at a hint:
const isAnagramB = function (s, t) {
const dictionary = {}
for (const letter of s) {
if (!dictionary[letter]) {
dictionary[letter] = 1
} else {
dictionary[letter]++
}
}
for (const letter of t) {
if (!dictionary[letter]) {
return false
} else {
dictionary[letter]--
}
}
for (const key in dictionary) {
if (dictionary[key] !== 0) {
return false
}
}
return true
}