Created
August 5, 2018 19:20
-
-
Save sevperez/e669af185acc8c93619ecff1bd027142 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isPalindrome(str) { | |
var reverse = str.split("").reverse().join(""); | |
return str === reverse; | |
} | |
function getCharCounts(chars) { | |
var charCounts = {}; | |
for (var i = 0, charLen = chars.length; i < charLen; i += 1) { | |
if (charCounts[chars[i]]) { | |
charCounts[chars[i]] += 1; | |
} else { | |
charCounts[chars[i]] = 1; | |
} | |
} | |
return charCounts; | |
} | |
function possiblePalindrome(str) { | |
if (isPalindrome(str)) { | |
return true; | |
} | |
var chars = str.split(""); | |
var charCounts = getCharCounts(chars); | |
var oddsCount = 0; | |
var charKeys = Object.keys(charCounts); | |
for (var i = 0, len = charKeys.length; i < len; i += 1) { | |
if (charCounts[charKeys[i]] % 2 === 1) { | |
oddsCount += 1; | |
} | |
if (oddsCount > 1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function palindromeCounter(str) { | |
str = str.toLowerCase(); | |
var words = str.split(" "); | |
var counter = 0; | |
for (var i = 0, len = words.length; i < len; i += 1) { | |
if (possiblePalindrome(words[i])) { | |
counter += 1; | |
} | |
} | |
return counter; | |
} | |
console.log(palindromeCounter("a")); // 1 ("a") | |
console.log(palindromeCounter("ab")); // 0 | |
console.log(palindromeCounter("Abc Def G")); // 1 ("g") | |
console.log(palindromeCounter("abbAc C ddEf")); // 2 ("abcba", "c") | |
console.log(palindromeCounter("lmn opq rst")); // 0 | |
console.log(palindromeCounter("AAA bAbbB")); // 2 ("aaa", "bbabb") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment