LeetCode 5. Longest Palindromic Substring

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值