<script>
// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
// A utility function to print
// a substring str[low..high]
// This function prints the
// longest palindrome substring (LPS)
// of str[]. It also returns the
// length of the longest palindrome
function longestPalSubstr(str)
{
let n = str.length; // calculating size of string
if (n < 2)
return n; // if string is empty then size will be 0.
// if n==1 then, answer will be 1(single
// character will always palindrome)
let maxLength = 1,start=0;
let low, high;
for (let i = 0; i < n; i++) {
low = i - 1;
high = i + 1;
while ( high < n && str[high] == str[i]) //increment 'high'
high++;
while ( low >= 0 && str[low] == str[i]) // decrement 'low'
low--;
while (low >= 0 && high < n && str[low] == str[high]){
low--;
high++;
}
let length = high - low - 1;
if (maxLength < length) {
maxLength = length;
start=low+1;
}
}
document.write("Longest palindrome substring is: ");
document.write(str.substring(start,maxLength+start));
return maxLength;
}
// Driver program to test above functions
let str = "forgeeksskeegfor";
document.write("</br>","Length is: " + longestPalSubstr(str),"</br>");
// This is code is contributed by shinjanpatra
</script>
/*
This implementation demonstrates how to
find the longest palindrome substring
in a given bigger string.
Let n be the length of the bigger string.
Time complexity: O(n^2)
Space complexity: O(1)
*/
public class LongestPalindromeSubstring {
public static void main(String[] args) {
String s = "babad";
System.out.println(longestPalindrome(s)); // bab
}
private static String longestPalindrome(String s) {
if (s.length() == 1) {
return s;
}
int maxLength = Integer.MIN_VALUE;
String longestPalindrome = "";
int n = s.length();
for (int index = 0; index < n; index++) {
for (int x = 0; index - x >= 0 && index + x < n; x++) {
if (s.charAt(index - x) == s.charAt(index + x)) {
int len = 2 * x + 1;
if (len > maxLength) {
maxLength = len;
longestPalindrome = s.substring(index - x, index + x + 1);
}
} else {
break;
}
}
}
for (int index = 0; index < n - 1; index++) {
for (int x = 1; index - x + 1 >= 0 && index + x < n; x++) {
if (s.charAt(index - x + 1) != s.charAt(index + x)) {
break;
} else {
int len = 2 * x;
if (len > maxLength) {
maxLength = len;
longestPalindrome = s.substring(index - x + 1, index + x + 1);
}
}
}
}
return longestPalindrome;
}
}