编程系列之:最长回文子串问题

本文介绍了一种利用栈来寻找给定字符串中最大回文子串长度的方法。通过逐字符对比并运用栈结构,该算法能高效地找出最长回文子串的长度。

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

 问题:
给定一个字符串,找出其中的最长回文子串长度。
例如:abccbabcddcba,最长的为abcddcba,长度为8

解决:
用栈,遇到与栈顶不同的字符,压栈;
否则,弹栈并比较下一个字符与栈顶的是否相同,相同继续弹栈;
记录弹了多少个,乘二,更新最长回文子串长度max;

/***
 * starstarstarpku@gmail.com
 * 20080404
 *
 * 找到给定字符串中最长的回文串长度。
 * 例如:
 * abccbabcddcba
 * 最长的回文串是abcddcba长度为8
 */

#include <stdio.h>
#include <string.h>
#include "../../data_structure/stack/include/sim_stack.h"

#define BUFFSIZE    512
void solve (const char *p)
{
    SimStack<char> stack;
    /**
     * 使用栈,如果当前字符与栈顶字符不同,则压栈;
     * 遇到相同的字符,弹栈并顺次比较直到不再相同,
     * 同时记录弹的字符数m;
     * 回压栈m个字符。
     * 继续压栈;
     */
    int n = strlen(p);
    int maxlen = 0;
    for (int i=0; i<n; ) {
        if (stack.size() <= 0 || stack.top() != p[i]) {
            stack.push(p[i]);
            i++;
            continue;
        }

        int index_bk = i;
        int popnum = 0;
        while (stack.size() > 0 && i < n && stack.top() == p[i]) {
            stack.pop();
            i++;
            popnum++;
        }
        // 记录最长回文子串长度
        if (2*popnum > maxlen) {
            maxlen = 2*popnum;
        }
        // 回压栈
        for (int j=index_bk-popnum; j<index_bk+popnum; j++) {
            stack.push (p[j]);
        }
    }
    printf ("longest huiwen string length is: %d/n", maxlen);
}

int main (int argc, char **argv)
{
    char str[BUFFSIZE];
    printf ("input a str: /n");
    scanf ("%s", str);
    solve (str);
    return 0;
}
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值