最长对称子字符串【最长回文子串】(动态规划)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/88532820

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 10000, INF = 1<<30;
string str, max_sub;
bool dp[MAX][MAX] = {0};

int main()
{
    cin>>str;
    if(str.size()) max_sub = str[0];
    for(int i=0; i<(int)str.size(); i++)
    {
        dp[i][i] = 1;
        if(i < (int)str.size()-1 && str[i] == str[i+1])
        {
            dp[i][i+1] = 1;
            max_sub = str.substr(i, 2);
        }
    }
    for(int L=3; L<=(int)str.size(); L++)
    {
        for(int i=0, j=i+L-1; j<(int)str.size(); i++, j++)
        {
            if(str[i] == str[j] && dp[i+1][j-1])
            {
                dp[i][j] = 1;
                max_sub = str.substr(i, L);
            }
            else dp[i][j] = 0;
        }
    }
    cout<<max_sub<<endl;
	return 0;
}



猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/88532820