Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考如下文章
https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong-tai-gui-hua-by-liweiwei1419/
char * longestPalindrome(char * s){
char d[1000][1000] ={0};
int i,j,curlen,start=0,maxlen=1;
int length = strlen(s);
for(j=1; j<length; j++){
for(i=0; i<j; i++){
if(s[i]==s[j])
if(j-i<3)
d[i][j] = 1;
else
d[i][j] = d[i+1][j-1];
if(d[i][j]){
curlen = j-i+1;
if(curlen > maxlen){
maxlen = curlen;
start = i;
}
}
}
}
if(length==0)
maxlen = 0;
*(s+start+maxlen) = 0;
return s+start;
}
void longestPart(char* s, int length, int left, int right, int* maxlen, int* start){
int curlen;
while(left >=0 && right<length){
if(s[left]==s[right]){
curlen =right-left+1;
if(curlen > *maxlen){
*maxlen = curlen;
*start = left;
}
left--;
right++;
}
else
break;
}
}
char * longestPalindrome(char * s){
int i,start=0,maxlen=1;
int length = strlen(s);
for(i=0; i<length; i++){
longestPart(s,length,i-1,i+1,&maxlen,&start);
}
for(i=0; i<length; i++){
longestPart(s,length,i,i+1,&maxlen,&start);
}
if(length==0)
maxlen=0;
*(s+start+maxlen) = 0;