Advertisement
imashutosh51

Longest Palindromic substring

Jul 25th, 2022 (edited)
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. class Solution {
  2.   public:
  3.     string longestPalin (string s) {
  4.         int n = s.size();
  5.         vector <vector <bool>> dp(n,vector<bool>(n,false));
  6.  
  7.         int max_len = 1,start = 0;;
  8.         for (int i = 0; i < n; ++i)   //one length substring will always be palindrome
  9.             dp[i][i] = true;
  10.            
  11.         for (int i = 0; i < n - 1; ++i) {
  12.             if (s[i] == s[i + 1]) {  //two length substring will be only palindrome if repeating eg aa,bb,cc
  13.                 dp[i][i + 1] = true;
  14.                 if(max_len<2){ start = i; max_len = 2; }
  15.             }
  16.         }
  17.        
  18.          /*so for abc:- a,b,c,ab,bc result are already in dp table,so for satisfying the palindromic
  19.         condition inside elemetnts must be palindrome so if assume a==c then b must be palindrome for being abc
  20.         palindrome that is already in dp table if that is palindrome or dp[i+1][j] where i and j is
  21.         corner index of current substring is true then we will compare a and c,if same then abc is
  22.         palindrome.
  23.         eg2 sbcbs,find bcb is palindrome or not using dp table i.e dp[i+1][j-1] if yes,then compare
  24.         ith and jt element,is same then it is palindrome else make dp[i][j]=false ie. not a palindrome
  25.         */
  26.              
  27.         for (int k = 3; k <= n; ++k) {   //cheking palindromne length from 3 to n
  28.             for (int i = 0; i < n - k + 1; ++i) {  //checking for every starting point
  29.                 int j = i + k - 1;    //ending point for current considered substring
  30.                 if (dp[i + 1][j - 1] && s[i] == s[j]) {
  31.                     dp[i][j] = true;
  32.      
  33.                     if (k > max_len) {
  34.                         start = i;
  35.                         max_len = k;
  36.                     }
  37.                 }
  38.             }
  39.         }
  40.         return s.substr(start,max_len);
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement