您的位置:首页 > 其它

LeetCode 5. Longest Palindromic Substring

2017-11-15 14:03 459 查看

Description

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: “babad

Output: “bab

Note: “aba” is also a valid answer.

Code

char* longestPalindrome(char* s) {
int n = strlen(s);
char *r = malloc(n*sizeof(char));
int max_l = 0;
int mid = (n % 2 == 0) ? n/2 : (n+1)/2;
int m, i, j;
i = j = mid-1;
if(n <= 1)
return s;
while((i+max_l/2)<n){
m = 0;
while((i-m>=0)&&(i+m<n)&&(s[i-m]==s[i+m])){
m++;
}
if(max_l < 2*(m-1)+1){
max_l = 2*(m-1)+1;
memcpy(r,&s[i-m+1],2*(m-1)+1);
}
if((i+1 < n)&&(s[i]==s[i+1])){
m = 0;
while((i-m>=0)&&(i+1+m<n)&&(s[i-m]==s[i+1+m])){
m++;
}
if(max_l < 2*m){
max_l = 2*m;
memcpy(r,&s[i-m+1],2*m);
}
}else if((i-1>=0)&&(s[i]==s[i-1])){
m = 0;
while((i-1-m>=0)&&(i+m<n)&&(s[i-1-m]==s[i+m])){
m++;
}
if(max_l < 2*m){
max_l = 2*m;
memcpy(r,&s[i-m],2*m);
}
}
i++;
}
while(j>=max_l/2){
if((j+1 < n)&&(s[j]==s[j+1])){
m = 0;
while((j-m>=0)&&(j+1+m<n)&&(s[j-m]==s[j+1+m])){
m++;
}
if(max_l < 2*m){
max_l = 2*m;
memcpy(r,&s[j-m+1],2*m);
}
}
if((j-1>=0)&&(s[j]==s[j-1])){
m = 0;
while((j-1-m>=0)&&(j+m<n)&&(s[j-1-m]==s[j+m])){
m++;
}
if(max_l < 2*m){
max_l = 2*m;
memcpy(r,&s[j-m],2*m);
}
}
m = 0;
while((j-m>=0)&&(j+m<n)&&(s[j-m]==s[j+m])){
m++;
}
if(max_l < 2*(m-1)+1){
max_l = 2*(m-1)+1;
memcpy(r,&s[j-m+1],2*(m-1)+1);
}
j--;
}
char *rr = malloc((max_l+1)*sizeof(char));
memset(rr,0,(max_l+1)*sizeof(char));
memcpy(rr,r,max_l);
return rr;
}


Discussions

1.Runtime: 6 ms

2.The algorithm starts searching from the middle to save some time, but the code seems longer than starting from left or right end.

3.To allocate the memory of a string in C, remember to allocate one more byte after the actual string length to keep the end char ‘\0’, or you will get a error char when in the end of the string.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: