DSA - longest Substring - C++,Dynamic Programming

Table of contents

No heading

No headings in the article.

Hey, so today we are going to solve Leetcode - Longest Palindromic Substring

Problem Link- https://leetcode.com/problems/longest-palindromic-substring/description/

class Solution {
public:
    string longestPalindrome(string s) {
    int n = s.length();
    int start = 0, maxLen = 1;
    bool table[n][n];
    memeset(table, 0, sizeof(table));

    for(int i =0; i<n; i++){
    table[i][i]=true;
}
    for(int i=0; n-1; i++){
    if(s[i] == s[i+1]){
    table[i][i+1] = true;
    maxLen=2;
    start=i;
}

    for(int k = 3; k<=n; k++){
      for(int i = 0; i<n-k+1; i++){
       int j = i+k-1; 

          if(table[i+1][j-1] && s[i]==s[j]){
          table[i][j] = true;

              if(k > maxLen){
              maxlen = k;
              start = i;
              }
          }
       }
     }
    return s.substr(start, maxLen);
}

}

In this implementation, we first create a boolean table table of size n x n, where n is the length of the input string s. The table is initialized to false for all values.

We then check for all substrings of length 1 and mark them as palindromes.

Next, we check for all substrings of length 2 and mark them as palindromes if both characters are equal.

We also keep track of the starting index and length of the longest palindromic substring found so far.

Finally, we check for all substrings of length 3 to n and fill the table table accordingly. We mark a substring as a palindrome if the substring between the i+1th and j-1th indices is a palindrome and if the ith and jth characters are equal. We update the starting index and length of the longest palindromic substring found so far if a longer palindrome is found.

At the end, we return the substring from the starting index and length of the longest palindromic substring found.

Note that the time complexity of this algorithm is O(n^2) and the space complexity is also O(n^2).