knakul853

Untitled

Jul 20th, 2020
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string convert(string s)
  4.     {
  5.         string news = "@";
  6.         int n = s.length();
  7.         for(int i=0;i<n;i++)
  8.         {
  9.             news+="#" + s.substr(i,1);
  10.         }
  11.         news+="#&";
  12.         return news;
  13.     }
  14.     string longestPalindrome(string s) {
  15.         int p[2005];
  16.         for(int i=0;i<2005;i++)p[i]=0;
  17.         string news = convert(s);
  18.         //cout<<news;
  19.         int n = news.length();
  20.         int c=0,r=0;
  21.         for(int i=1;i<n-1;i++)
  22.         {
  23.             int mirror = 2*c-i;
  24.             if(r > i) p[i] = min(p[mirror],r-i);
  25.            
  26.             while(news[i + 1 + p[i]] == news[i -1 -p[i]])p[i]++;
  27.            
  28.             if(i+p[i]>r)r =i+p[i],c=i;
  29.         }
  30.         int id=0,mx=0;
  31.         for(int i=1;i<n-1;i++)
  32.         {
  33.             if(mx<p[i])mx = p[i],id=i;
  34.         }
  35.        
  36.         string ans = s.substr((id - mx -1)/2,mx);
  37.         return ans;
  38.        
  39.     }
  40. };
Add Comment
Please, Sign In to add comment