Palindrome Partitioning II(找给定字符串分割次数获取回文字串, 动态规划)

/***
Palindrome Partitioning IIMar 19518 / 34344
Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

题目大意:给出一个字符串,求出最小分割次数,使得分割出来的字符串是回文
 
 思路:动态规划。从后面开始往前遍历,从字串起点i开始到j的字串为回文,那么
       就分为两种情况:1、i-j为一段  2、i-j不为一段,两种情况取分割较少的为
       dp[i] = min(dp[i], dp[j+1] + 1) 
*/

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;


int minCut(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
   int   length = s.size();
   int dp[length+1];
   bool isPalin[length][length];
   
   //首先初始化dp数组,长度为length时,最小分割次数为0,长度为0时,分割次数为length-1 
   for(int i=0; i<=length; i++)
     dp[i] = length - i;
     
   //isPalin[i][j] 表示从i到j之间的子串是否回文 
   for(int i=0; i<length; i++)
     for(int j=0; j<length; j++)
        isPalin[i][j] = false;
        
   for(int i=length-1; i>=0; i--){
       for(int j=i; j<length; j++){
          //如果子串i-j的头尾相同,如果此时子串长度为2或除掉头尾i和j的字串也是回文,那么该i-j的串也是回文 
          if(s[i] == s[j] && (j - i <= 1 || isPalin[i+1][j-1])){
                isPalin[i][j] = true;
                dp[i] = min(dp[i], dp[j+1] + 1);  //比较当前回文串i-j与i-j之后的j起始点比较,取小的一个 
          }        
       }        
   }
   
   return dp[0]-1;
}
int main()
{
    string s ;
    cin >> s;
    cout << minCut(s) << endl;
    
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值