面试题94:删除最少字符,使字符串为回文串

题目:

给定一个字符串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;
}


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值