
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Longest Palindromic Substring in Python
Suppose we have a string S. We have to find the longest palindromic substring in S. We are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the longest palindromic substring is “BAB”.
To solve this, we will follow these steps
- Define one square matrix of order same as the length of string, and fill it with False
- Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1
- start := 0
- for l in range 2 to length of S + 1
- for i in range 0 to length of S – l + 1
- end := i + l
- if l = 2, then
- if S[i] = S[end - 1], then
- DP[i, end - 1] = True, max_len := l, and start := i
- if S[i] = S[end - 1], then
- otherwise
- if S[i] = S[end - 1] and DP[i + 1, end - 2], then
- DP[i, end - 1] = True, max_len := l, and start := i
- if S[i] = S[end - 1] and DP[i + 1, end - 2], then
- for i in range 0 to length of S – l + 1
- return a substring of from index start to start + max_len
Example(Python)
Let us see the following implementation to get better understanding −
class Solution(object): def longestPalindrome(self, s): dp = [[False for i in range(len(s))] for i in range(len(s))] for i in range(len(s)): dp[i][i] = True max_length = 1 start = 0 for l in range(2,len(s)+1): for i in range(len(s)-l+1): end = i+l if l==2: if s[i] == s[end-1]: dp[i][end-1]=True max_length = l start = i else: if s[i] == s[end-1] and dp[i+1][end-2]: dp[i][end-1]=True max_length = l start = i return s[start:start+max_length] ob1 = Solution() print(ob1.longestPalindrome("ABBABBC"))
Input
"ABBABBC"
Output
"BBABB"
- Related Articles
- Longest Palindromic Substring
- Program to find length of longest palindromic substring in Python
- Program to find length of longest palindromic substring after single rotation in Python
- Longest Palindromic Subsequence
- Longest Palindromic Subsequence in C++
- Longest Substring Without Repeating Characters in Python
- SequenceMatcher in Python for Longest Common Substring.
- Program to find length of longest palindromic subsequence in Python
- Program to find longest awesome substring in Python
- Java Program for Longest Palindromic Subsequence
- Find longest consecutive letter and digit substring in Python
- Program to find longest nice substring using Python
- Longest Repeating Substring in C++
- Longest Duplicate Substring in C++
- Program to find out the length of longest palindromic subsequence using Python

Advertisements