forked from yogain123/AlgoCasts-JS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagram.js
More file actions
30 lines (23 loc) · 860 Bytes
/
anagram.js
File metadata and controls
30 lines (23 loc) · 860 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
//one string is an anagram of other strings, if it uses the same character in same quantity not
//considering spaces or special character
//let word = "resadsdasd%%%!!!!!";
//console.log(word.replace(/[^\w]/g, "")); // it remove all special characters and space
console.log(anagram('rail safety', 'fairy tales')) // True
function anagram(stringA, stringB) {
const aCharMap = buildMap(stringA);
const bChatMap = buildMap(stringB);
if (Object.keys(aCharMap).length !== Object.keys(bChatMap).length)
return false;
for (let char in aCharMap) {
if (aCharMap[char] !== bChatMap[char])
return false;
}
return true;
}
function buildMap(str) {
const charMap = {};
for (let char of str.replace(/[^\w]/g, "").toLowerCase()) {
charMap[char] = charMap[char] + 1 || 1;
}
return charMap;
}