Total Accepted: 82026 Total Submissions: 379898 Difficulty: Medium
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Subscribe to see which companies asked this question
Hide Similar Problems
1.动态规划
class Solution { public: string longestPalindrome(string s) { int sSize = s.size(); if(sSize <=1){ return s; } int start = 0; int maxLen = 1; bool help[1000][1000] = {false}; for(int i=0;i<sSize;i++){ help[i][i] = true; if(i>0 && s[i-1]==s[i]){ help[i-1][i] = true; start = i-1; maxLen = 2; } } for(int len = 3;len<=sSize;len++){ for(int i=0;i<=sSize-len;i++){ int j = i+len-1; if(help[i+1][j-1] && s[i]==s[j]){ help[i][j] = true; start = i; maxLen = len; } } } return s.substr(start,maxLen); } };
2.中心扩展
3.manacher
class Solution { public: void preProcess(string &s,int sSize,string& copedStr){ for(int i=0;i<sSize;i++){ copedStr.push_back('*'); copedStr.push_back(s[i]); } copedStr.push_back('*'); } string longestPalindrome(string s) { int sSize = s.size(); if(sSize<=1){ return s; } string str; preProcess(s,sSize,str); int strSize = 2*sSize+1; vector<int> parr(strSize,1); int mid = 0; int left =-1,right = 1; int pl = -1, pr = 1; int radius = 0; for(;right<strSize;right++){ radius = 0; if(right>=pr){ while((right-radius>=0 && right+radius<strSize) && str[right-radius]==str[right+radius]){ radius++; } parr[right] = radius; }else{ left = mid - (right-mid); if(left - parr[left] +1 < pl+1){ parr[right] = left - pl; }else if(left - parr[left] +1 > pl+1){ parr[right] = parr[left]; }else{ radius = parr[left]-1; while((right-radius>=0 && right+radius<strSize) && str[right-radius]==str[right+radius]){ radius++; } parr[right] = radius; } } radius = parr[right] ; if(right + radius >= pr){ pr = right + radius ; pl = right - radius ; mid = right; } } int maxLen = 0, pos = 0; for(int i=1;i<strSize;i++){ int tmpRadius = i%2==0 ? parr[i]-1:parr[i]; if(tmpRadius>maxLen ){ pos = i; maxLen = parr[i]-1; } } string res; for(int i=pos-maxLen;i<=pos+maxLen;i++){ if(i%2!=0){ res.push_back(str[i]); } } return res; } };