Created
July 31, 2019 04:23
-
-
Save wataruoguchi/3d803a32ae7348f03ffa431d24472f14 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
// 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