psd面试

经过学习,终于搞清楚了最长回文子串的计算方法算法和该题的题意。

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 1300;
char str[maxn];
int dp[maxn][maxn];

int main()
{
	int len;
	while(scanf("%s",str) != EOF)
	{
		memset(dp,0,sizeof(dp));
		len = strlen(str);
		for(int i = 0; str[i] != '\0'; i++)
		{
			if(str[i] <= 'Z' && str[i] >= 'A')
			{
				str[i] += 32;
			}
		}
		for(int i = len - 1; i >= 0; i--)
		{
			dp[i][i] = 1;
			for(int j = i + 1; j < len; j++)
			{
				if(str[i] == str[j])
				{
					dp[i][j] = dp[i + 1][j - 1] + 2;
				}
				else
				{
					dp[i][j] = max(dp[i + 1][j],dp[i][j - 1]);
				}
			}
		}
		printf("%d\n",len - dp[0][len - 1]);
	}

	return 0;

}

猜你喜欢

转载自blog.csdn.net/someone_and_anyone/article/details/79745475