leetcode-#5 Longest Palindromic Substring

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

char * longestPalindrome(char * s){
    int len = strlen(s);
    int maxSubStrLen = 0;
    int startIdx, endIdx;
    int searchIdx = 0, searchLen = 1;
    int i, m, n;
    if (len <= 1) {
        return s;
    }
    while (searchIdx < len) {
        for (i = searchIdx + 1; i < len; i++){
            if (s[searchIdx] != s[i]) {
                break;
            }
            searchLen++;
        }
        m = i;
        n = searchIdx - 1;
        while ((n >= 0) && (m < len)) {
            if (s[n] != s[m]) {
                break;
            }
            m++;
            n--;
            searchLen += 2;   
        }
        if (searchLen > maxSubStrLen){
            maxSubStrLen = searchLen;
            startIdx = n + 1;
            endIdx = m - 1;
        }
        searchLen = 1;
        searchIdx ++;
    }
    s[endIdx + 1] = '\0';
    return &s[startIdx];
}

作者:yang-le-duo-48
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/cyu-yan-bian-li-xian-zhao-zhong-xin-zi-chuan-zai-c/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


#define max(a,b) (((a) > (b)) ? (a) : (b))

char * longestPalindrome(char * s){
    int start = 0, end = 0;
    int len = 0;
    int len1 = 0;
    int len2 = 0;
    
    if (strlen(s) <= 1) 
        return s;
    
    for (int i = 0; i < strlen(s); i++) {
        len1 = expandaroundcenter(s, i, i);
        len2 = expandaroundcenter(s, i, i+1);
        len = max(len1, len2);
        if (len > end - start) {
            start = i - ((len - 1)>>1);
            end = i + (len>>1);
        }
    }
    char *p = malloc(sizeof(char) * (end - start + 2));
    strncpy(p, s + start, end - start + 1);
    p[end - start + 1] = '\0';
    return p;
}

int expandaroundcenter(char *s, int left, int right)
{
    int L = left, R = right;
    while (L >= 0 && R < strlen(s) && s[L] == s[R]) {
        L--;
        R++;
    }
    return R - L - 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值