当前位置:网站首页>codeup最长回文子串

codeup最长回文子串

2022-06-22 17:50:00 Douglas_LT

codeup最长回文子串

#pragma warning(disable :4996)
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include <stdio.h>
#include<string> 
#include<vector>
#include<algorithm>
#include<map>
using namespace std;

int dp[5010][5010] = {
     0 };


int main()
{
    
	string str;
	str.resize(5010, '\0');
	vector<pair<char, int>>str_change;
	scanf("%[^\n]", &str[0]);
	int len1 = str.length();
	for (int i = 0; i < len1; i++)
	{
    
		if (isalpha(str[i]))
		{
    
			str_change.push_back(make_pair(toupper(str[i]), i));
		}
	}
	
	int len = str_change.size();
	int maxn = 1;
	for (int i = 0; i < len - 1; i++)
	{
    
		dp[i][i] = 1;
		if (str_change[i].first == str_change[i + 1].first)
		{
    
			dp[i][i + 1] = 1;
		}
	}
	dp[len - 1][len - 1] = 1;
	int  startn = 0, endn = 0;
	for (int i = 0; i < len - 1; i++)
	{
    
		if (str_change[i].first== str_change[i + 1].first)
		{
    
			startn = i;
			endn = i + 1;
			maxn = 2;
			break;
		}
	}
	
	for (int j = 2; j <= len; j++)
	{
    
		for (int i = 0; i + j < len; i++)
		{
    
			if (str_change[i].first == str_change[i + j].first&&dp[i + 1][i + j - 1])
			{
    
				dp[i][i + j] = 1;
				if (j + 1 > maxn)
				{
    
					maxn = j + 1;
					startn = str_change[i].second;
					endn = str_change[i + j].second;
				}
			}
		}
	}
	for (int i = startn; i <= endn; i++)
	{
    
		cout << str[i];
	}
	return 0;
}

加粗样式

原网站

版权声明
本文为[Douglas_LT]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Douglas_LT/article/details/109961183