import scala.annotation.tailrec
/**
* find longest palindrome (length only)
*
* @param s
* @return
*/
def longestPalindromeLength(s: String): Int = {
@tailrec def check(prev: Int, next: Int, acc: Int): Int = {
if (prev < 0 || next >= s.length || s(prev) != s(next)) acc
else check(prev - 1, next + 1, acc + 2)
}
var maxLength = 0
for (i <- 0 until s.length) {
// check odd length and even length
maxLength = maxLength max check(i, i, -1) max check(i, i + 1, 0)
}
maxLength
}
longestPalindromeLength("")
longestPalindromeLength("a")
longestPalindromeLength("bab")
longestPalindromeLength("baab")
/**
* find longest palindrome (substring)
*
* @param s
* @return
*/
def longestPalindrome(s: String): String = {
@tailrec def check(prev: Int, next: Int, acc: Int): Int = {
if (prev < 0 || next >= s.length || s(prev) != s(next)) acc
else check(prev - 1, next + 1, acc + 2)
}
var maxLength, length, index = 0
for (i <- 0 until s.length) {
length = check(i, i, -1) max check(i, i + 1, 0)
maxLength = maxLength max length
if (length == maxLength) index = i
}
// recover string from index and length
val diff = maxLength / 2
maxLength match {
case l if l % 2 == 0 => s.subSequence(index - diff + 1, index + diff + 1).toString
case _ => s.subSequence(index - diff, index + diff + 1).toString
}
}
longestPalindrome("bananas")
longestPalindrome("abracadabra")