βLongest Palindromic Substring
Brute Force
inline bool isPlaindrome(string::iterator begin, string::iterator end) {
while(begin < end)
if(*(begin++) != *(end--))
return false;
return true;
}
string Solution::longestPalindrome(string A) {
int longest = INT_MIN;
string res = "";
for(int i = 0; i < A.size(); i++)
for(int j = i; j < A.size(); j++)
if(j - i + 1 > longest)
if(isPlaindrome(A.begin() + i, A.begin() + j)) {
res = A.substr(i, j - i + 1);
longest = j - i + 1;
}
return res;
}
Time Complexity:
Where isPalindrome(str)
takes β time and generating all the substrings take β time.
Space Complexity: β for the result.
Efficient Solution
void getLargePalindromAt(const string &str, int left, int right, int &resLen, string &res) {
while(left >= 0 && right < str.size() && str[left] == str[right]) {
if(right - left + 1 > resLen) {
resLen = right - left + 1;
res = str.substr(left, right - left + 1);
}
left--, right++;
}
}
string Solution::longestPalindrome(string A) {
string res = "";
int resLen = 0;
for(int center = 0; center < A.size(); center++){
int left = center, right = center;
getLargePalindromAt(A, left, right, resLen, res);
left = center, right = center + 1;
getLargePalindromAt(A, left, right, resLen, res);
}
return res;
}
Time Complexity: β
Space Complexity: β for the result
Logic: Assume each letter as a centre of a palindrome and expand outward while checking if it is a palindrome.
Edge Case: Even Length palindrome.
Last updated