Longest Palindromic Substring Algorithm

The Longest Palindromic Substring Algorithm is a computational method used to identify the longest contiguous sequence of characters within a given string that is also a palindrome. A palindrome is a word, phrase, number, or sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. This algorithm aims to find the longest such sequence in a given input string, which has numerous applications in areas such as data compression, computational biology, and natural language processing. There are several techniques to implement this algorithm, including the brute force approach, dynamic programming, and an optimized method called Manacher's algorithm. The brute force approach involves checking all possible substrings for palindromes, which has a time complexity of O(n^3). Dynamic programming provides a more efficient solution with a time complexity of O(n^2) and space complexity of O(n^2), where n is the length of the input string. Manacher's algorithm, on the other hand, is the most optimized approach with linear time complexity O(n) and constant space complexity, making it the preferred choice for solving this problem in practical applications.
class Solution {
public:
    string longestPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int beg = 0, end = 0;
        int longest = 1;
        
        for (int i = 0; i < s.size(); i++) {
            dp[i][i] = dp[i+1][i] = true;
        }
        for (int d = 1; d < s.size(); d++) {
            for (int i = 0, j = i + d; j < s.size(); i++, j++) {
                dp[i][j] = false;
                if (s[i] == s[j]) dp[i][j] |= dp[i+1][j-1];
                if (dp[i][j] && longest < j-i+1) {
                    beg = i, end = j;
                }
            }
        }
        return s.substr(beg, end - beg + 1);
    }
private:
    static const int MAXN = 1010;
    bool dp[MAXN][MAXN];
};

LANGUAGE:

DARK MODE: