Maximum length palindromic substring for every index such that it starts and ends at that index

In this article, we'll delve into a fascinating problem in the realm of string algorithms: how to find the maximum length palindromic substring for every index such that it starts and ends at that index in a string. This problem is an interesting challenge, especially for those interested in mastering the art of string manipulation in C++.

A palindrome is a string that reads the same backward as forward. For example, "madam" is a palindrome. The challenge here is to find the longest palindromic substring for every index in a given string, where the substring starts and ends at that specific index.

Problem Statement

Given a string, find the maximum length palindromic substring for every index such that the substring starts and ends at that index.

Approach

The approach we'll use to solve this problem is called "Manacher's Algorithm". This algorithm works by expanding around the center and is known for its efficiency in finding the longest palindromic substring. It uses previously computed information to avoid redundant computation, which makes it significantly faster than naive solutions.

Example

#include<bits/stdc++.h>
using namespace std;

vector<int> findLongestPalindromicSubstring(string s) {
int n = s.size();
vector<int> d1(n);
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && s[i - k] == s[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
return d1;
}

int main() {
string s = "bananas";
vector<int> result = findLongestPalindromicSubstring(s);
for(int i=0; i<s.size(); i++){
cout << "Index: " << i << ", String: " << s.substr(i-result[i]+1, 2*result[i]-1) << ", Length: " << 2*result[i]-1 << "\n";
}
return 0;
}


Output

Index: 0, String: b, Length: 1
Index: 1, String: a, Length: 1
Index: 2, String: ana, Length: 3
Index: 3, String: anana, Length: 5
Index: 4, String: ana, Length: 3
Index: 5, String: a, Length: 1
Index: 6, String: s, Length: 1


The function findLongestPalindromicSubstring takes as input a string s and returns a vector of integers where each index i of the vector stores the maximum length of the palindromic substring starting and ending at index i in the string.

In this test case, the input string is "bananas". The findLongestPalindromicSubstring function is called with this string as the argument, and the result is stored in the result vector. Then, for each index, the corresponding maximum length palindromic substring is printed along with its length.

Conclusion

Finding the maximum length palindromic substring for every index in a string can be a challenging problem, but with the right algorithm at hand, such as Manacher's Algorithm, it can be solved efficiently. We hope this article has given you a clear understanding of how to approach and solve this problem in C++.

Updated on: 18-May-2023

49 Views