Created
July 1, 2018 21:46
-
-
Save sevperez/3babc7efb2b253f2e6d5ad2d357abfba 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
I think there may be an issue with your solution here? Although I'm not sure how the code could be fixed, maybe you could chime in?
console.log(palindromeCounter("abbAc C ddEf")); // 2 ("abcba", "c")
This line should return 3. As the three palindromes would be:
"abcba"
"bacab"
"c"