给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢? 输出需要删除的字符个数。

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include <algorithm>  
#include<iomanip>
#include<string>

using namespace std;

int getStr(string str1, string str2)
{
	string str;
	int m = str1.size();
	int n = str2.size();
	vector<vector<int>> vec(m+1, vector<int>(n+1, 0));
	for (int i = 1; i <= m; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			if (str1[i-1] == str2[j-1]) //这里注意是i-1 和j-1相比较
			{
				vec[i][j] = vec[i - 1][j - 1] + 1;
		
			}
			else
			{
				vec[i][j] = max(vec[i-1][j], vec[i][j-1]);
			}
		}
	}

	return vec[m][n];
}

int main()
{



		
	string str1;
	while (cin>>str1)
	{
		string str2 = str1;
		reverse(str1.begin(),str1.end());
		cout << "str1:" << str1 << endl;
		cout << "str2:" << str2 << endl;
		cout << str1.size() - getStr(str1, str2) << endl;
	}

		
		
		
	

	


	
	return 0;
}
原文地址:https://www.cnblogs.com/wdan2016/p/6657516.html