Skip to content

Add string check anagram #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 19, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions String/CheckAnagram.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Anagram check is case sensitive; i.e. Aba and aba is not a anagram.
// inputs are strings i.e. str1 and str2
const checkAnagram = (str1, str2) => {
// check that inputs are strings.
if (typeof str1 !== 'string' || typeof str2 !== 'string') {
return 'Not string(s)'
}

// If both strings have not same lengths then they can not be anagram.
if (str1.length !== str2.length) {
return 'Not Anagram'
}

// Use hashmap to keep count of characters in str1

const str1CharCount = new Map()

for (let i = 0; i < str1.length; i++) {
let previousCount = 0
if (str1CharCount.has(str1[i])) {
previousCount = str1CharCount.get(str1[i])
}
str1CharCount.set(str1[i], previousCount + 1)
}

// Now check if second string has same characters?

for (let i = 0; i < str2.length; i++) {
let previousCount = 0
// if str1CharCount has no key for str2[i] then not anagram.
if (!str1CharCount.has(str2[i])) {
return 'Not anagrams'
}
previousCount = str1CharCount.get(str2[i])
str1CharCount.set(str2[i], previousCount - 1)
}

// Now check if all entries in hashmap has zeros.

for (const key in str1CharCount) {
if (str1CharCount[key] !== 0) { return 'Not anagrams' }
}

return 'Anagrams'
}

console.log(checkAnagram('abcd', 'bcad')) // should print anagram
console.log(checkAnagram('abcd', 'abef')) // should print not anagram
console.log(checkAnagram(10, 'abcd'))// should print Not String(s).
console.log(checkAnagram('abs', 'abds'))// should print not anagram