动态规划——回文串最小分割数

题目:

给定一个字符串str,返回把str全部切成回文子串的最小分割数。


举例:

str="ABA" ,不需要切割,返回0;

str="ACDCDCDAD",最少需要切两次,比如"A","CDCDC","DAD",所以返回2.


解题思路:动态规划
 状态定义:
 DP [i]:表示子串( 0 ,i)的最小回文切割数,则最优解在DP[s.length- 1 ]中。(0,i)的子串中包括了i+1个字符,最多分割i次。
 状态转移定义
   1 .初始化:当字串str[0]--str[i] (包括i位置的字符)是回文时,DP[i] =  0 (表示不需要分割);否则,DP[i] = i(表示至多分割i次);
   2 .对于任意大于 1 的i,如果str[j]--str[i] ( 1 <= j <=  i ,即遍历i之前的每个子串)是回文时,DP[i] = min(DP[i], DP[j- 1 ]+ 1 ); 
   (注:j不用取0是因为若j == 0,则又表示判断(0,i))。

代码:
#include <string>
#include <vector>
#include <iostream>
#include<algorithm>
using namespace std;

bool IsPalindrome(const char* str, int begin, int last)//判断str[begin]--str[last]是否为回文串
{
	int nbegin = begin;
	int nlast = last;
	while(nbegin<nlast)
	{
		if (str[nbegin]!=str[nlast])
		   return false;
		nbegin++;
		nlast--;
	}
	return true;
}


int main( )
{	
	string strIn;
	cin>>strIn;
	int nlen = strIn.length();
	vector<int> vecDP(nlen,0);
	for (int i=1;i<nlen;i++)
	{
		vecDP[i] = IsPalindrome(strIn.c_str(),0,i)?0:i;//初始化,若为回文串则直接为0
		for (int j=i;j>0;j--)
		{
			if (IsPalindrome(strIn.c_str(),j,i))
			{
				vecDP[i] = min(vecDP[i],vecDP[j-1]+1);//状态转移
			}
		}
	}
	cout<<vecDP[nlen-1];//输出结果

	return 0;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值