[leetcode] 132. Palindrome Partitioning II

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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.

Example:

Input:

"aab"

Output:

1

Explanation:

The palindrome partitioning ["aa","b"] could be produced using 1 cut.

分析

题目的意思是:给定一个字符串,现在分成几个字串,使得每个字串都是回文子串,求最小的分隔数。

  • 定义状态数组: dp[n], dp[j]表示从0到j(包含j)的子串所需要用到的最小的切割次数
    状态转移方程: 当子串str[i…j]是一个回文子串时, dp[j] = min(dp[i-1] + 1, dp[i])
    动态规划,设字符串的的坐标为0,1,…,i,i+1,…,j,j+1。如果i~j是回文子串,那么最小切分次数等于前i个字符串的切分数+1,或者当前的切分数目。即dp[j+1] = min(dp[j+1],dp[i]+1)

代码

class Solution {
public:
    int minCut(string s) {
        if(s.empty()){
            return 0;
        }
        int n=s.length();
        vector<vector<bool>> p(n,vector<bool>(n));
        vector<int> dp(n);
        for(int i=0;i<n;i++){
            dp[i]=i;
            for(int j=0;j<=i;j++){
                if(s[i]==s[j]&&(i-j<2||p[j+1][i-1])){
                    p[j][i]=true;
                    if(j==0){
                        dp[i]=0;
                    }else{
                        dp[i]=min(dp[i],dp[j-1]+1);
                    }
                }
            }
        }
        return dp[n-1];
    }
};

参考文献

[编程题]palindrome-partitioning-ii
[LeetCode] Palindrome Partitioning II 拆分回文串之二

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值