given a stringSlargonorte, the task is to find the length oflongest palindromic substringof a given string.
Examples:
Forbidden:S = “abcbab”
Salida:5
Explanation:
The string "abcba" is the longest substring that is a palindrome of length 5.Forbidden:S = “abcdaa”
Salida:2
Explanation:
the string "aa" is the longest substring that is a palindrome of length 2.
Recommended: Test your approach in {IDE} first before moving on to the solution.
Naive approach:The simplest approach to solving the problem isgenerate all possible substrings of the given stringand print the length oflongest substringwhich is apalindrome.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using
namespace
standard;
// Function to get the length of
// longest palindromic substring
And t
maislongPalSubstr(string string)
{
// Length of the given string
And t
n = str.size();
// Store the maximum length
And t
maxLength = 1, start = 0;
// Iterate over a string
for
(
And t
yo = 0;
i < str.longitud(); i++) {
// Iterate over a string
for
(
And t
j = them;
j < str.length(); j++) {
And t
bandera = 1;
// Check the palindrome
for
(
And t
k = 0;
k < (j - i + 1) / 2; k++)
con
(str[i + k]
!= cadena[j - k])
bandera = 0;
// Se cadena [i, j - i + 1]
// is palindrome
con
(bandera
&& (j - i + 1) > maxLength) {
start = me;
compromisomax = j - i + 1;
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
And t
principal()
{
// Given string
string string =
"forgeekskeegfor"
;
// Function call
cout << pero longoPalSubstr(str);
return
0;
}
Java
// Java program for the above approach
matter
java.io.*;
classroom
GFG{
// Function to get the length of
// longest palindromic substring
static
And t
longestPalSubstr(String str)
{
// Length of the given string
And t
n = str.length();
// Store the maximum length
And t
max length =
1
, start =
0
;
// Iterate over a string
for
(
And t
ue =
0
; i < str.longitud(); i++)
{
// Iterate over a string
for
(
And t
j = yo; j < str.longitud(); j++)
{
And t
bandera =
1
;
// Check the palindrome
for
(
And t
k =
0
;
k < (j - i +
1
) /
2
; k++)
con
(str.charAt(i + k) !=
str.charAt(j - k))
bandera =
0
;
// Se cadena [i, j - i + 1]
// is palindrome
con
(bandera !=
0
&&
(j-yo +
1
) > maximum length)
{
start = me;
maximum length = j - i +
1
;
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
public
static
empty
principal (String[] argumentos)
{
// Given string
string =
"forgeekskeegfor"
;
// Function call
System.out.print(longestPalSubstr(str));
}
}
// This code is contributed by code_hunt
Python3
# Python3 program for the above approach
# Function to get the length of
# the longest palindromic substring
definitely
maislongoPalSubstr(
calle
):
# Length of the given string
norte
=
Len
(
calle
)
# Store the maximum length
maximum length
=
1
to start
=
0
# Iterate over a string
for
UE
they
range
(
Len
(
calle
)):
# Iterate over a string
for
j
they
range
(UE,
Len
(
calle
),
1
):
bandera
=
1
# fetch palindrome
for
k
they
range
((j
-
UE
+
1
)
/
/
2
):
con
(
calle
[UE
+
k] !
=
calle
[j
-
k]):
bandera
=
0
# Se cadena [i, j - i + 1]
# is palindrome
con
(bandera !
=
0
mi
(j
-
UE
+
1
) > maximum length):
to start
=
UE
maximum length
=
j
-
UE
+
1
# LPS return length
return
maximum length
# driver code
# given string
calle
=
"forgeekskeegfor"
# function call
print
(longerPalSubstr(
calle
))
# This code is contributed by code_hunt
C #
// C# program for the above approach
using
System;
classroom
GFG{
// Function to get the length of
// longest palindromic substring
static
And t
maislongoPalSubstr(
rope
calle)
{
// Length of the given string
And t
n = string length;
// Store the maximum length
And t
maxLength = 1, start = 0;
// Iterate over a string
for
(
And t
yo = 0; i < str.Length; i++)
{
// Iterate over a string
for
(
And t
j = yo; j < str.Length; j++)
{
And t
bandera = 1;
// Check the palindrome
for
(
And t
k = 0;
k < (j - i + 1) / 2; k++)
con
(str[i + k] != str[j - k])
bandera = 0;
// Se cadena [i, j - i + 1]
// is palindrome
con
(bandera != 0 &&
(j - i + 1) > maximum length)
{
start = me;
compromisomax = j - i + 1;
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
public
static
empty
Principal ()
{
// Given string
rope
string =
"forgeekskeegfor"
;
// Function call
Console.Write(longestPalSubstr(str));
}
}
// This code is contributed by code_hunt
JavaScript
<script>
// JavaScript program for the above approach
// Function to get the length of
// longest palindromic substring
function
maislongPalSubstr(str)
{
// Length of the given string
era
n = string length;
// Store the maximum length
era
maxLength = 1, start = 0;
// Iterate over a string
for
(
era
yo = 0;
i < str.longitud; i++) {
// Iterate over a string
for
(
era
j = them;
j < str.length; j++) {
era
bandera = 1;
// Check the palindrome
for
(
era
k = 0;
k < (j - i + 1) / 2; k++)
con
(str[i + k]
!= cadena[j - k])
bandera = 0;
// Se cadena [i, j - i + 1]
// is palindrome
con
(bandera
&& (j - i + 1) > maxLength) {
start = me;
compromisomax = j - i + 1;
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
// Given string
era
string =
"forgeekskeegfor"
;
// Function call
document.write( más longoPalSubstr(str));
</script>
Salida:
10
Time complexity:ABOUT3), where N is the length of the given string.
Auxiliary Space:ABOUT)
dynamic programmingGetting closer:The above approach can be optimized by storing the results ofOverlapping subproblems. The idea is similar tothis post. Below are the steps:
- keep a boolean valuetable[N][N]that is filled from the bottom up.
- The value ofmeat[i][j]true if the substring is a palindrome, false otherwise.
- Calculatemeat[i][j], check the value ofmeat[i + 1][j – 1], if the value is true andstring[i]is the same asstring[j], then updatemeat[i][j]TRUE.
- Otherwise, the value ofmeat[i][j]is updated as false.
Below is the illustration of the chain."freaks":
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using
namespace
standard;
// Function to find the length of
// longest palindromic substring
And t
maislongPalSubstr(string string)
{
// Length of string str
And t
n = str.size();
// Store states of dp
bool
table[n][n];
// Initialize table[][] to false
set of members
(tabla, 0,
size of
(low hill));
// All substrings of length 1
// are palindromes
And t
max length = 1;
for
(
And t
i = 0; i < n; ++ i)
tabla[i][i] =
TRUE
;
// Check substring of length 2
And t
start = 0;
for
(
And t
i = 0; I < n - 1; ++ i) {
// if adjacent characters are equal
con
(string[i] == string[i + 1]) {
// Update table[i][i + 1]
tabla[i][i + 1] =
TRUE
;
start = me;
max length = 2;
}
}
// Check lengths greater than 2
// k is the length of the substring
for
(
And t
k = 3; k <= n; ++k) {
// Set the initial index
for
(
And t
i = 0; i < n - k + 1; ++ i) {
// Finish the index of the substring
// of length k
And t
j = i + k - 1;
// fetch palindrome
// subcadena str[i, j]
con
(board[i + 1][j - 1]
&& string[i] == string[j]) {
// Mark as true
board[i][j] =
TRUE
;
// Update the maximum length
con
(k > max length) {
start = me;
max length = k;
}
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
And t
principal()
{
// Given character string
string string =
"forgeekskeegfor"
;
// Function call
cout << pero longoPalSubstr(str);
return
0;
}
Java
// Java program for the above approach
matter
java.util.*;
classroom
GFG{
// Function to find the length of
// longest palindromic substring
static
And t
longestPalSubstr(String str)
{
// Length of string str
And t
n = str.length();
// Store states of dp
boleano
[][] tabla =
nuevo
boleano
[n][n];
// All substrings of length 1
// are palindromes
And t
max length =
1
;
for
(
And t
ue =
0
; i < n; ++ i)
tabla[i][i] =
TRUE
;
// Check substring of length 2
And t
start =
0
;
for
(
And t
ue =
0
; I <n-
1
; ++ yo)
{
// if adjacent characters are equal
con
(str.charAt(i) == str.charAt(i +
1
))
{
// Update table[i][i + 1]
mesa[i][i +
1
] =
TRUE
;
start = me;
max length =
2
;
}
}
// Check lengths greater than 2
// k is the length of the subString
for
(
And t
k =
3
; k <= n; ++ k)
{
// Set the initial index
for
(
And t
ue =
0
; i < n - k +
1
; ++ yo)
{
// end of subString index
// of length k
And t
j = i + k -
1
;
// fetch palindrome
// substring string[i, j]
con
(mesa[i +
1
][j-
1
] &&
str.charAt(i) == str.charAt(j))
{
// Mark as true
board[i][j] =
TRUE
;
// Update the maximum length
con
(k > maximum length)
{
start = me;
max length = k;
}
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
public
static
empty
main(String[] argumentos)
{
// string given str
string =
"forgeekskeegfor"
;
// Function call
System.out.print(longestPalSubstr(str));
}
}
// This code is contributed by Amit Katiyar
C #
// C# program for
// the previous approach
using
System;
classroom
GFG{
// Function to find the length of
// longest palindromic substring
static
And t
longestPalSubstr(String str)
{
// Length of string str
And t
n = string length;
// Store states of dp
bool
[,] tabla =
nuevo
bool
[n, n];
// All substrings of length 1
// are palindromes
And t
max length = 1;
for
(
And t
i = 0; i < n; ++ i)
tabla[i, i] =
TRUE
;
// Check the substring
// about length 2
And t
start = 0;
for
(
And t
i = 0; I < n - 1; ++ i)
{
// if adjacent characters are equal
con
(string[i] == string[i + 1])
{
// Update table[i,i + 1]
tabla[i, i + 1] =
TRUE
;
start = me;
max length = 2;
}
}
// Check lengths greater than 2
// k is the length of the subString
for
(
And t
k = 3; k <= n; ++ k)
{
// Set the initial index
for
(
And t
i = 0; i < n - k + 1; ++ i)
{
// end of subString index
// of length k
And t
j = i + k - 1;
// fetch palindrome
// substring string[i, j]
con
(board[i + 1, j - 1] &&
string[i] == string[j])
{
// Mark as true
board[i, j] =
TRUE
;
// Update the maximum length
con
(k > maximum length)
{
start = me;
max length = k;
}
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
public
static
empty
Principal(String[] argumentos)
{
// string given str
string =
"forgeekskeegfor"
;
// Function call
Console.Write(longestPalSubstr(str));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python program for the above approach
# Function to find the length of
# the longest palindromic substring
definitely
maislongoPalSubstr(
calle
):
# String length str
norte
=
Len
(
calle
);
# Store dp states
low hill
=
[[
FALSE
for
UE
they
range
(norte)]
for
j
they
range
(norte)];
# All substrings of length 1
# are palindromes
maximum length
=
1
;
for
UE
they
range
(norte):
mesa[i][i]
=
TRUE
;
# Check substring of length 2
to start
=
0
;
for
UE
they
range
(norte
-
1
):
# if adjacent characters are equal
con
(
calle
[UE]
=
=
calle
[UE
+
1
]):
# update table[i][i + 1]
mesa[i][i
+
1
]
=
TRUE
;
to start
=
UE;
maximum length
=
2
;
# Check lengths greater than 2
# k is the length of the subString
for
k
they
range
(
3
, norte
+
1
):
# set initial index
for
UE
they
range
(norte
-
k
+
1
):
# end of subString index
# of length k
j
=
UE
+
k
-
1
;
# check palindromic
# substring string[i, j]
con
(tabla I
+
1
][j
-
1
]
mi
calle
[UE]
=
=
calle
[j]):
# Mark as true
meat[i][j]
=
TRUE
;
# update the maximum length
con
(k > maximum length):
to start
=
UE;
maximum length
=
k;
# LPS return length
return
maximum length;
# driver code
con
__name__
=
=
'__principal__'
:
# string given str
calle
=
"forgeekskeegfor"
;
# function call
print
(longerPalSubstr(
calle
));
# This code is contributed by 29AjayKumar
JavaScript
<script>
// javascript program for the above approach
// Function to find the length of
// longest palindromic substring
function
maislongPalSubstr(string) {
// Length of string str
era
n = string length;
// Store states of dp
era
tabela = Array(n).fill().map(()=>Array(n).fill(
FALSE
));
// All substrings of length 1
// are palindromes
era
max length = 1;
for
(
era
i = 0; i < n; ++ i)
tabla[i][i] =
TRUE
;
// Check substring of length 2
era
start = 0;
for
(i = 0; i < n - 1; ++i) {
// if adjacent characters are equal
con
(str.charAt(i) == str.charAt(i + 1)) {
// Update table[i][i + 1]
tabla[i][i + 1] =
TRUE
;
start = me;
max length = 2;
}
}
// Check lengths greater than 2
// k is the length of the subString
for
(k = 3; k <= n; ++k) {
// Set the initial index
for
(i = 0; i < n - k + 1; ++i) {
// end of subString index
// of length k
era
j = i + k - 1;
// fetch palindrome
// substring string[i, j]
con
(tabela[i + 1][j - 1] && str.charAt(i) == str.charAt(j)) {
// Mark as true
board[i][j] =
TRUE
;
// Update the maximum length
con
(k > max length) {
start = me;
max length = k;
}
}
}
}
// Returns the LPS length
return
maximum length;
}
// controller code
// string given str
era
string =
"forgeekskeegfor"
;
// Function call
document.write(longestPalSubstr(str));
// This code is contributed by umadevi9616
</script>
Salida:
10
Time complexity:ABOUT2), where N is the length of the given string.
Auxiliary Space:ABOUT)
efficient approach:To optimize the above approach, the idea is to useManacher algorithm. Using this algorithm, for each characterC, the longest palindromic substring havingChow can you find its center whose length is odd. But the longest palindromic substring can also have a uniform length that has no center. So some special characters can be added between each character.
For example, if the given string is"bababc"then it will become“$#a#b#a#b#a#b#c#@”. Now notice that in this case, for each characterC, the longest palindromic substring with centerCit will have an odd length.
Below are the steps:
- Add the special characters in the given stringSas explained above and let its length benorte.
- initialize an arrayd[], center andrcom0whered[I]stores the length of the left side of the palindrome whereY]It is the center,rdenotes the rightmost visited boundary, and center denotes the current index of the character that is the center of that rightmost boundary.
- When walking the ropeS, for each indexUE, sei is less than rthen your answer was previously calculated andd[I]can be set to equal to take into account the mirror of the character inUEwith the center which can be calculated as(2*center – i).
- Now check that there are a few characters after the r so that the palindrome gets longer and longer.
- Se(i + d[i]) is greater than r, update r =(i + d[i])and center asUE.
- After finding the longest palindrome for each characterCas the center, print the maximum value of(2*d[i] + 1)/2where0 ≤ i < nbecaused[I]stores only the left part of the palindrome.
Below is the implementation of the above approach:
C++14
// C++ program for the above approach:
#include <bits/stdc++.h>
using
namespace
standard;
// Function that placed '#' in between
// before and after each character
cadena UpdatedString(cadena s){
string newstring =
"#"
;
// loop through the string
for
(
auto
ch : s){
novaString += canal;
novastring +=
"#"
;
}
// Returns the string
return
novaString;
}
//Function that finds the length of
// longest palindromic substring
And t
admin(string s){
// Update the string
s = updated string(s);
// Store the longest suitable prefix
// which is also a suffix
And t
LPS[s.longitud()] = {};
And t
C = 0;
And t
R = 0;
for
(
And t
yo = 0; i < s.longitud() ; i++){
And t
imir = 2 * C - i;
// Find the minimum length of
// the palindrome
con
(R > yo){
LPS[i] = min(R-i, LPS[imir]);
}
other
{
// Find the actual length of
// the palindrome
LPS[i] = 0;
}
// Exception handling
while
(((i + 1 + LPS[i]) < s.comprimento()) && ((i - 1 - LPS[i]) >= 0) && s[i + 1 + LPS[i]] == s [i - 1 - LPS[i]]){
LPS[i] += 1;
}
// Update C and R
con
(i + LPS[i] > R){
C = yo;
R = i + LPS[i];
}
}
And t
r = 0, c = -1;
for
(
And t
yo = 0; i < s.longitud() ; i++){
r = máx(r, LPS[i]);
con
(r == LPS[i]){
c = yo;
}
}
// Returns the length r
return
r;
}
// controller code
And t
principal()
{
// Given character string
string string =
"forgeekskeegfor"
;
// Function call
cout << Manacher(cadena) << endl;
}
// This code is contributed by subhamgoyal2014.
Java
// Java code for the above approach
matter
java .util .matrices;
classroom
GFG {
// Function that placed '#' in between
// before and after each character
static
String updated String(String s) {
String novaString =
"#"
;
// loop through the string
for
(
Characters
ch: s.toCharArray()) {
novaString += canal;
novastring +=
"#"
;
}
// Returns the string
return
novaString;
}
//Function that finds the length of
// longest palindromic substring
static
And t
Manager(String s) {
// Update the string
s = updated string(s);
// Store the longest suitable prefix
// which is also a suffix
And t
[] LPS =
nuevo
And t
[s.length()];
And t
C =
0
;
And t
R =
0
;
for
(
And t
ue =
0
; i < s.longitud(); i++) {
And t
play =
2
* C - yo;
// Find the minimum length of
// the palindrome
con
(R > yo) {
LPS[i] = Math.min(R - i, LPS[imir]);
}
other
{
// Find the actual length of
// the palindrome
LPS[i] =
0
;
}
// Exception handling
while
(((ue +
1
+ LPS[i]) < s.longitud()) && ((i -
1
-LPS[i]) >=
0
) && (s.charAt(i +
1
+ LPS[i]) == s.charAt(i -
1
- LPS[i]))) {
LPS[i] +=
1
;
}
// Update C and R
con
(i + LPS[i] > R) {
C = yo;
R = i + LPS[i];
}
}
And t
r =
0
;
for
(
And t
ue =
0
; i < s.longitud(); i++) {
r = Math.max(r, LPS[i]);
}
// Returns the length r
return
r;
}
// controller code
public
static
empty
main(String[] argumentos) {
// Given character string
string =
"forgeekskeegfor"
;
// Function call
System.out.println(Manacher(str));
}
}
// This code is contributed by lokeshpotta20.
Python3
# Python program for the above approach
# Function that puts '#' in between
# before and after each character
definitely
Updated string (string):
novaString
=
[
'#'
]
# traverse the string
for
Characters
they
rope:
novaString
+
=
[Characters,
'#'
]
# returns the string
return
''.join(nuevaCadena)
# Function that finds the length of
# the longest palindromic substring
definitely
Manager(string):
# update a string
rope
=
updated string (string)
# Store the longest suitable prefix
# which is also a suffix
LPS
=
[
0
for
_
they
range
(
Len
(corda))]
C
=
0
R
=
0
for
UE
they
range
(
Len
(corda)):
juice
=
2
*
C
-
UE
# Find the minimum length of
# the palindrome
con
R > yo:
LPS[yo]
=
min
(R
-
yo, LPS[imir])
other
:
# Find the actual length of
# the palindrome
LPS[yo]
=
0
# Exception handling
attempt
:
while
string[i
+
1
+
LPS[i]] \
=
=
string[i
-
1
-
LPS[i]]:
LPS[yo]
+
=
1
except
:
to spend
# Update C and R
con
UE
+
LPS[i] > R:
C
=
UE
R
=
UE
+
LPS[yo]
r,c
=
maximum
(LPS), LPS.índice(
maximum
(LPS))
# Returns the length r
return
r
# controller code
# string given str
calle
=
"forgeekskeegfor"
# function call
print
(Manager(
calle
))
C #
// C# program to implement the above approach
using
System;
using
System.Collections;
using
System.Collections.Generic;
classroom
GFG
{
// Function that placed '#' in between
// before and after each character
static
rope
updatedstring(
rope
s){
rope
newstring =
"#"
;
// loop through the string
for each
(
Characters
CH
they
s){
novaString += canal;
novastring +=
"#"
;
}
// Returns the string
return
novaString;
}
//Function that finds the length of
// longest palindromic substring
static
And t
Manager(
rope
s){
// Update the string
s = updated string(s);
// Store the longest suitable prefix
// which is also a suffix
And t
[] LPS =
nuevo
And t
[s.Longitude];
And t
C = 0;
And t
R = 0;
for
(
And t
yo = 0; i < s.Length ; i++){
And t
imir = 2 * C - i;
// Find the minimum length of
// the palindrome
con
(R > yo){
LPS[i] = Math.Min(R-i, LPS[imir]);
}
other
{
// Find the actual length of
// the palindrome
LPS[i] = 0;
}
// Exception handling
while
(((i + 1 + LPS[i]) < s.Longitud) &&
((i - 1 - LPS[i]) >= 0) &&
s[i + 1 + LPS[i]] == s[i - 1 - LPS[i]]){
LPS[i] += 1;
}
// Update C and R
con
(i + LPS[i] > R){
C = yo;
R = i + LPS[i];
}
}
And t
r = 0;
for
(
And t
yo = 0; i < s.Length ; i++){
r = Math.Max(r, LPS[i]);
}
// Returns the length r
return
r;
}
// controller code
public
static
empty
Principal(
rope
[] arguments){
// Given character string
rope
string =
"forgeekskeegfor"
;
// Function call
Console.WriteLine(Manacher(str));
}
}
// This code is contributed by Entertain2022.
JavaScript
//Javascript code for the above approach
// Function that placed '#' in between
// before and after each character
function
updated string(string) {
let nuevaCadena = [
'#'
];
// loop through the string
for
(leave the string character) {
nuevaCadena.push(char,
'#'
);
}
// Returns the string
return
nuevaCadena.join(
''
);
}
//Function that finds the length of
// longest palindromic substring
function
manager(string) {
// Update the string
string = updated string(string);
// Store the longest suitable prefix
// which is also a suffix
happening LPS =
nuevo
Array(string.length).fill(0);
sea C = 0;
sea R = 0;
for
(let i = 0; i < string.length; i++) {
sea imir = 2 * C - i;
// Find the minimum length of
// the palindrome
con
(R > yo) {
LPS[i] = Math.min(R-i, LPS[imir]);
}
other
{
// Find the actual length of
// the palindrome
LPS[i] = 0;
}
// Exception handling
attempt
{
while
(cadena[i + 1 + LPS[i]] === cadena[i - 1 - LPS[i]]) {
LPS[i] += 1;
}
}
to take
(Error) {
// to spend
}
// Update C and R
con
(i + LPS[i] > R) {
C = yo;
R = i + LPS[i];
}
}
sea r = Math.max(...LPS);
sea c = LPS.indexOf(r);
// Returns the length r
return
r;
}
// controller code
// Given character string
sea str =
"forgeekskeegfor"
;
// Function call
console.log(Administrator(str));
Salida:
10
Time complexity:O(N), where N is the length of the given string.
Auxiliary Space:ABOUT)
my personal notesarrow_fall_up