Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wataruoguchi/3d803a32ae7348f03ffa431d24472f14 to your computer and use it in GitHub Desktop.
Save wataruoguchi/3d803a32ae7348f03ffa431d24472f14 to your computer and use it in GitHub Desktop.
// https://www.geeksforgeeks.org/given-a-string-print-all-possible-palindromic-partition/
function findAllPalindromes(str) {
function isPalindrome(str, min, max) {
while (min < max) {
if (str[min] !== str[max]) return false;
min++;
max--;
}
return true;
}
function findPS(str, start, len) {
if (start >= len) return;
let idx;
for (idx = start; idx < len; idx++) {
if (isPalindrome(str, start, idx)) {
const palindrome = str.substr(start, idx - start + 1);
if (!palindromes.find((str) => str === palindrome)) {
palindromes.push(palindrome);
}
findPS(str, idx + 1, len);
}
}
}
let palindromes = [];
findPS(str, 0, str.length);
return palindromes;
}
const string = 'geeks and keeks';
const res = findAllPalindromes(string);
console.log(res, res.join(',') === ["g","e","k","s"," ","a","n","d","ee","keek"].join(','));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment