Last active
September 21, 2015 12:26
-
-
Save sourcedelica/160c6f488be63e05ae59 to your computer and use it in GitHub Desktop.
This file contains 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
def palindromePartitions(s: String): Seq[Seq[String]] = { | |
val n = s.length - 1 | |
def isPalindrome(i: Int, j: Int): Boolean = | |
i >= j || s.charAt(i) == s.charAt(j) && isPalindrome(i + 1, j - 1) | |
// Palindromes starting at s[i] | |
def partition(i: Int): Seq[Seq[String]] = | |
if (i == n + 1) Seq(Seq()) | |
else for { | |
j <- i to n // For each s[i..j] where j=i..n | |
if isPalindrome(s, i, j) // If s[i..j] is a palindrome | |
ps <- partition(j + 1) // For each palindrome starting at s[j+1] | |
} yield s.substring(i, j + 1) +: ps // Prepend s[i..j] to it | |
partition(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment