Leetcode 5.Longest Palindromic Substring

本文分享了LeetCode上第5题Longest Palindromic Substring的C语言实现过程,通过双层循环查找回文串,并记录最长回文子串的位置。文章最后附上了GitHub地址供读者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从这个月开始刷leetcode的题,由于水平有限,欢迎交流和提宝贵的意见。

下面是我对 5.Longest Palindromic Substring 的实现。

char *longestPalindrome(char *s)
{
    unsigned long len;
    int count;
    int start,end;
    int l,r;
    int max;


    len = strlen(s);
    if (len < 2) return s;
    start = 0;
    end = 0;
    max = 0;
    l = 0;
    r = 0;
    for (int i = 0; i < len; i++) {
        for (int j = i + 1; j < len; j++) {
            if (s[i] == s[j]) {
                count = j - i + 1;
                if (count % 2 != 0) {
                    start = count / 2;
                    end = start;
                } else {
                    start = count / 2 - 1;
                    end = start + 1;

                }
                while (start > i && end < j && s[start] == s[end]) {
                    start--;
                    end++;

                }
                if (s[start] != s[end]) {
                    break;
                }else {
                    if (end - start + 1 > max) {
                        max = end - start + 1;
                        l = start;
                        r = end;
                    }
                }
            } else {
                continue;
            }


        }
    }
    s[r+1] = '\0';

    return s+l;


}

下面是本人github地址:https://github.com/WolfgangBai/leetcode-c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值