-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_anagrams.js
More file actions
38 lines (32 loc) · 809 Bytes
/
check_anagrams.js
File metadata and controls
38 lines (32 loc) · 809 Bytes
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
function areAnagrams(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
let count = {};
for (let i = 0; i < str1.length; i++) {
count[str1[i]] = (count[str1[i]] || 0) + 1;
}
for (let i = 0; i < str2.length; i++) {
if (!count[str2[i]]) {
return false;
}
count[str2[i]]--;
}
return true;
}
console.log(areAnagrams("listen", "silent"));
console.log(areAnagrams("hello", "world"));
console.log(areAnagrams("mest", "stem"));
function areAnagram(str1, str2) {
const normalize = (str) =>
str
.toLowerCase()
.replace(/[^a-z0-9]/g, "")
.split("")
.sort()
.join("");
return normalize(str1) === normalize(str2);
}
// Example usage:
console.log(areAnagram("listen", "silent"));
console.log(areAnagram("hello", "world"));