Skip to content

Instantly share code, notes, and snippets.

@sevperez
Created July 1, 2018 21:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sevperez/3babc7efb2b253f2e6d5ad2d357abfba to your computer and use it in GitHub Desktop.
Save sevperez/3babc7efb2b253f2e6d5ad2d357abfba to your computer and use it in GitHub Desktop.
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")
@JustinWouters
Copy link

JustinWouters commented Feb 25, 2022

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment