Longest palindromic substring Python code example
Example 1: how to find the longest string python
max(a_list, key=len)
Example 2: longest palindromic substring python
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"))
Example 3: find all the palindrome substring in a given string
using namespace std;
// expand in both directions of low and high to find all palindromes
void expand(string str, int low, int high, auto &set)
{
// run till str[low.high] is a palindrome
while (low >= 0 && high < str.length()
&& str[low] == str[high])
{
// push all palindromes into the set
set.insert(str.substr(low, high - low + 1));
// expand in both directions
low--, high++;
}
}
// Function to find all unique palindromic substrings of given string
void allPalindromicSubstrings(string str)
{
// create an empty set to store all unique palindromic substrings
unordered_set<string> set;
for (int i = 0; i < str.length(); i++)
{
// find all odd length palindrome with str[i] as mid point
expand(str, i, i, set);
// find all even length palindrome with str[i] and str[i+1] as
// its mid points
expand(str, i, i + 1, set);
}
// print all unique palindromic substrings
for (auto i : set)
cout << i << " ";
}
int main()
{
string str = "google";
allPalindromicSubstrings(str);
return 0;
}