题目:
给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符的个数。
思路:
先求字符串s的反转串rs,然后求s和rs的最大公共子序列(子序列和子串的区别是子序列不要求连续,子串要求连续),则最大公共子序列的长度即为最大回文串的长度。(注意:字符串和其反转串的最大公共子序列一定是对称的,即回文)
关于求两个字符串s1和s2的最长公共子序列,可以用动态规划来做。
DP[i][j]表示s1左边i个字符与s2左边j个字符的最大公共子串,则有以下关系:
if s1[i]==s2[j] DP[i][j]=1+DP[i-1][j-1]
else DP[i][j]=max(DP[i-1][j], DP[i][j-1])
实现:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string converseString(string str){
int size = str.size();
if (size < 2) return str;
int front = 0, rear = size - 1;
while(front < rear){
char temp = str[front];
str[front] = str[rear];
str[rear] = temp;
front++;
rear--;
}
return str;
}
int max(int a, int b){
return a>b ? a : b;
}
int GetLCS(string s1, string s2){
int size = s1.size();
int curMax = 0;
vector<vector<int> > DP(size + 1, vector<int>(size + 1, 0));
for (int i = 0; i <= size; i++)
{
DP[i][0] = 0;
DP[0][i] = 0;
}
for (int i = 1; i <= size; i++)
for (int j = 1; j <= size; j++){
if (s1[i - 1] == s2[j - 1])
DP[i][j] = DP[i - 1][j - 1] + 1;
else
DP[i][j] = max(DP[i][j - 1], DP[i - 1][j]);
if (DP[i][j] > curMax)
curMax = DP[i][j];
}
return curMax;
}
int core(string str){
string converseStr = converseString(str);
return str.size() - GetLCS(str, converseStr);
}
int main(int argc, char* argv[])
{
cout << core("google") << endl;
return 0;
}