Java Program to find Longest Palindromic Substring

Finding the longest palindromic substring in a given string is a classic problem in computer science. There are several approaches to solve this problem, but one of the most efficient methods is using the “Expand Around Center” approach. This approach has a time complexity of O(n^2), which is efficient for this problem.

CODE:

import java.util.*;

class GFG {

// Function to print a subString str[low..high]
static void printSubStr(String str, int low, int high)
{
for (int i = low; i <= high; ++i)
System.out.print(str.charAt(i));
}

static int longestPalSubstr(String str)
{

int n = str.length();

int maxLength = 1, start = 0;

for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
int flag = 1;

for (int k = 0; k < (j – i + 1) / 2; k++)
if (str.charAt(i + k)
!= str.charAt(j – k))
flag = 0;

if (flag != 0 && (j – i + 1) > maxLength) {
start = i;
maxLength = j – i + 1;
}
}
}

System.out.print(
“Longest palindrome substring is: “);
printSubStr(str, start, start + maxLength – 1);

return maxLength;
}

public static void main(String[] args)
{
String str = “forCodeSpeedyfor”;
System.out.print(“\nLength is: ”
+ longestPalSubstr(str));
}
}

OUTPUT:

Longest palindrome substring is: CodeSpeedy
Length is: 10

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top