查找最长回文子串


/*
https://leetcode.cn/problems/longest-palindromic-substring/?favorite=2cktkvj

给你一个字符串 s,找到 s 中最长的回文子串。

如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。

*/


/*
I got two methonds:
1. do as each char as the center of a palindromic to check the length,
    its time O(N*N)
2. revert the string as string, find orig-string and revert-string max
   common same substring, it shall be a O(N*N) time & O(N*N) space
*/

// here use the 1 methond

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void find_max_palindrome_string(const char *str)
{
    int length = strlen(str);
    int max = 0, start = 0, pos = 0, i = 0;

    for (pos = 0; pos < length; pos++) {

        //str[pos] as center of palindrome string
        for (i = 1; ((pos - i) >= 0) && ((pos + i) < length); i++) {
            if (str[pos -i] != str[pos + i])
                break;
        }

        int tmp = 2 * (i - 1) + 1;
        if (tmp > max) {
            max = tmp;
            start = pos + 1 - i;
        }

        if (str[pos] != str[pos + 1])
            continue;

        //if str[pos] == str[pos + 1], it could be even length
        for (i = 1; ((pos - i) >= 0) && ((pos + 1 + i) < length); i++) {
            if (str[pos -i] != str[pos + 1 + i])
                break;
        }

        tmp = 2 * i;
        if (tmp > max) {
            max = tmp;
            start = pos + 1 - i;
        }    
    }

    printf("max palindrome string: len=%d, from=%d, string: ", max, start);
    for (i = 0; i < max; i++) {
        putchar(str[i + start]);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("To find the max palindrom string, please input a string!\n");
        return 0;
    }

    find_max_palindrome_string(argv[1]);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值