最长回文子串

问题描述

  给出一个字符串S,求S的最长回文子串的长度

题目分析

  这道题可以用动态规划来做。

  第一步:设d[ i ][ j ] 为来表示 s[ i ] 到 s[ j ]所表示的字符串是否是回文串,是则为1,不是则为0

  第二步:寻找状态转移方程

    1.若s[ i ] == s[ j ] ,则 s[ i ] 到 s[ j ] 表示的字符串是否为回文串取决于 d[ i - 1][ j + 1]

     因此,d[ i ][ j ] = d[ i - 1 ][ j + 1]

    2.若s[ i ] != s[ j ] ,则d[ i ][ j ] = 0

\[d[i][j] = \left\{ {\begin{array}{*{20}{c}}
{d[i][j] = d[i - 1][j + 1],{\rm{S}}[{\rm{i}}]{\rm{ = = S}}[{\rm{j}}]}\\
{0,{\rm{S}}[{\rm{i}}]!{\rm{ = S}}[{\rm{j}}]}
\end{array}} \right.\]

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <cmath>
using namespace std;
char s[105];
int len_s;
int d[105][105];
int max_t = 1;
void dp() {
    for (int l = 3; l <= len_s; l++) {//枚举长度
        for (int i = 0; i + l - 1 < len_s; i++) {//枚举子串起点
            int j = i + l - 1;//子串终点
            if (s[i] == s[j] && d[i + 1][j - 1] == 1) {
                d[i][j] = 1;
                max_t = l;//更新最长回文子串长度 
            }
        }
    }
}
void init() {
    for (int i = 0; i < len_s; i++) {
        d[i][i] = 1;
        if (i < len_s - 1 && s[i] == s[i + 1]) {
            d[i][i + 1] = 1;
            max_t = 2;
        }
    }
}
int main() {
    scanf("%s", s);
    len_s = strlen(s);
    init();
    dp();
    cout << max_t;
    return 0;
}

参考:

https://www.cnblogs.com/coderJiebao/p/Algorithmofnotes30.html

posted @ 2019-03-02 11:52  阳离子  阅读(173)  评论(0编辑  收藏  举报