Javatpoint Logo
Javatpoint Logo

Longest Palindrome String

In this tutorial, we will learn to write the Python program to find the longest substring in Python. In this problem, we have given a string and we need to find the longest substring in that first string. Let's understand the following examples.

Example - 1:

Example - 2:

We can solve this problem using various methods. Let's see the following solution.

Naïve Approach

In this simple approach, we check each substring whether a substring is a palindrome or not in the substring with the higher length first. Following are the step to achieve the idea.

  • Create substrings from the provided string in such a way that longer substrings are generated first.
  • To achieve this, implement a loop where the iterator 'LEN' ranges from the length of the given string down to 1, where 'N' represents the length of the given string.
  • Execute a nested loop and define an iterator 'j' that will indicate the starting index of the substring.
  • Extract the substring starting from index 'j' up to 'j + LEN'.
  • If the extracted substring is a palindrome, then return it as it represents the longest possible palindrome substring with the smallest starting index.

Let's implement the Python code -

Example -

Output:

"bab"

Explanation -

First, we define a is_palindrome(s) function that checks if a given string `s` is a palindrome. It does this by comparing the original string with its reverse. If they are the same, it returns `True`, indicating that the string is a palindrome; otherwise, it returns `False`.

Then we define longest_palindrome_substring(input_str) function to find the longest palindrome the substring from the input string `input_str`.

It follows the steps we defined earlier.

  • We calculate the length of the input string and store it in the variable `n`.
  • Then Initialize an empty string longest_palindrome` to store the longest palindrome substring found.
  • We run a loop starting from the length of the input string (`n`) down to 1, in reverse order. It represents the length of the substrings we'll generate, starting from the longest possible length down to length 1.
  • Then we run the second loop for start_index in range(n - length + 1 that iterates over the possible starting indices of the substrings for the given `length`. Since we want substrings of length `length`, we need to ensure that the starting index doesn't go beyond `n - length`.
  • Extract the substring starting from the current `start_index` and with length `length`.
  • Check if the `substring` is a palindrome (using the `is_palindrome` helper function) and if its length is greater than the length of the `longest_palindrome` found so far.
  • If the above condition is met, update the `longest_palindrome` to the current `substring`.
  • After both loops are completed, return the `longest_palindrome`, which represents the longest palindrome substring in the input string.
  • In the example usage, `input_str = "babad"`, and the function returns the longest palindrome substring "bab", which is then printed as the output.

Finding probable first and last of Palindrome

The concept is to determine the potential last character of a palindrome for each character in the string. Then, verify if the substring ending at that potential last character is a palindrome and update the length of the palindrome accordingly.

Below are the steps to implement this concept.

  • Run a loop to iterate through each character of the string.
  • Inside this loop, run another nested loop to check if any other characters are the same as the current character.
  • If a matching character is found, it is possible that both characters could form the first and last characters of a potential palindrome substring.
  • Store this substring and check if it is the longest palindrome found so far.
  • If it is indeed the longest palindrome, store it and continue iterating through the remaining characters to find other potential palindromes.

Once all the iterations are completed, the function should return the longest palindromic substring that has been found during the process. This substring represents the longest palindrome present in the given input string.

Let's understand the following example -

Example -

Output:

"bab"

Explanation -

  • The function longestPalSubstr(s) takes a string s as input and finds the longest palindrome substring in it.
  • The variable longest is used to store the longest palindrome substring found so far.
  • The first loop (for i in range(n)) iterates through each character of the input string.
  • The second loop (for j in range(n-1, i, -1)) iterates in reverse order from the end of the string towards the current character i.
  • Inside the nested loops, the code checks whether the characters at indices i and j are the same. If they are the same and the length of the current substring is greater than the length of the longest palindrome found so far, it checks if the substring and its reverse are equal. If they are equal, it updates the longest palindrome.
  • After both loops are completed, the code prints the longest palindrome substring.
  • If no longest palindrome substring is found, it returns the first character of the input string.
  • The example usage is given with stri = "babad", and the code prints the longest palindrome substring "bab".

Longest Palindrome Substring using Dynamic Programming

The core concept of this approach is to leverage the knowledge of the palindrome status of a substring [i, j] to determine the status of the substring [i-1, j+1]. If the substring from i to j is not a palindrome, then the substring from i-1 to j+1 will also not be a palindrome. Conversely, if str[i-1] and str[j+1] are the same, then the substring from i-1 to j+1 will be a palindrome.

To apply this idea, we create a 2D table (let's call it 'table') that stores the status of substrings str[i . . . j]. We then check for substrings of length from 1 to N. For each length, we examine all possible substrings starting from each character 'i' and determine whether it is a palindrome or not using the aforementioned logic. The length of the longest palindrome formed will be the required answer.

Let's understand the following example -

Example -

Output:

bab

Explanation -

  • The longest_palindromic_substring(input_str) function takes a string input_str as input and returns the longest palindromic substring.
  • It creates a 2D table 'table' to store the status of substrings. Each cell table[i][j] will be True if the substring from input_str[i] to input_str[j] is a palindrome.
  • First, it marks all substrings of length 1 as palindromes (since single characters are palindromes).
  • Next, it checks for substrings of length 2 and marks them as palindromes if the characters at both ends are the same.
  • Then, it checks for substrings of length greater than 2 using nested loops. For each length, it iterates through all possible substrings starting at each index 'i' and checks if the first and last characters are the same and the substring inside them (i+1 to j-1) is a palindrome. If both conditions are met, it marks the substring as a palindrome.
  • During this process, it keeps track of the start index and length of the longest palindromic substring found.
  • Finally, it returns the longest palindromic substring using the start index and length.
  • The example usage tests the function with input_str = "babad" and prints the longest palindromic substring "bab".






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA