Skip to content

Commit 47dfc59

Browse files
authored
Add string check anagram (TheAlgorithms#254)
* Add CheckAnagram.js to String Algorithms that checks if Strings are anagrams * Add CheckAnagram.js to String Algorithms that checks if Strings are anagrams * Add CheckAnagram.js to String Algorithms that checks if Strings are anagrams
1 parent b443875 commit 47dfc59

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

String/CheckAnagram.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Anagram check is case sensitive; i.e. Aba and aba is not a anagram.
2+
// inputs are strings i.e. str1 and str2
3+
const checkAnagram = (str1, str2) => {
4+
// check that inputs are strings.
5+
if (typeof str1 !== 'string' || typeof str2 !== 'string') {
6+
return 'Not string(s)'
7+
}
8+
9+
// If both strings have not same lengths then they can not be anagram.
10+
if (str1.length !== str2.length) {
11+
return 'Not Anagram'
12+
}
13+
14+
// Use hashmap to keep count of characters in str1
15+
16+
const str1CharCount = new Map()
17+
18+
for (let i = 0; i < str1.length; i++) {
19+
let previousCount = 0
20+
if (str1CharCount.has(str1[i])) {
21+
previousCount = str1CharCount.get(str1[i])
22+
}
23+
str1CharCount.set(str1[i], previousCount + 1)
24+
}
25+
26+
// Now check if second string has same characters?
27+
28+
for (let i = 0; i < str2.length; i++) {
29+
let previousCount = 0
30+
// if str1CharCount has no key for str2[i] then not anagram.
31+
if (!str1CharCount.has(str2[i])) {
32+
return 'Not anagrams'
33+
}
34+
previousCount = str1CharCount.get(str2[i])
35+
str1CharCount.set(str2[i], previousCount - 1)
36+
}
37+
38+
// Now check if all entries in hashmap has zeros.
39+
40+
for (const key in str1CharCount) {
41+
if (str1CharCount[key] !== 0) { return 'Not anagrams' }
42+
}
43+
44+
return 'Anagrams'
45+
}
46+
47+
console.log(checkAnagram('abcd', 'bcad')) // should print anagram
48+
console.log(checkAnagram('abcd', 'abef')) // should print not anagram
49+
console.log(checkAnagram(10, 'abcd'))// should print Not String(s).
50+
console.log(checkAnagram('abs', 'abds'))// should print not anagram

0 commit comments

Comments
 (0)