LeetCode: Palindrome Partitioning II [132]
来源:互联网 发布:python文本编辑器推荐 编辑:程序博客网 时间:2024/06/05 14:31
【题目】
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.
【题意】
给定一个字符串s, 返回最小切割次数,是的所有的切割子串都为回文。【思路】
DP,依次确定s[1...n]的最小分割次数假设用minCuts[i]表示,以第i结尾的字符串的最小切分次数。
那么怎么确定minCuts[i]. 我们已知了minCuts[j] j=0,1,...,i-1
对于i之前的每个位置j, 如果s[j+1,..,i]为回文串,则j为切割点的最小切割次数就是minCuts[j]+1;
所以我们要从所有的j中取一个位置使得i位置的切割次数最小的位置作为切割点,即minCuts[i]=min{minCuts[j]+1} s[j+1,..,i]是回文,j=0,1...i-1
【代码】
class Solution {public: int minCut(string s) { int len=s.length(); if(len==0||len==1)return 0; //构造回文判别矩阵 vector<vector<bool> > isPal(len, vector<bool>(len, false)); //初始化isPal[i][i] for(int i=0; i<len; i++) isPal[i][i]=true; //初始化isPal[i][i+1] for(int i=0; i<len-1; i++) if(s[i]==s[i+1])isPal[i][i+1]=true; //初始化其他i<j的子串 for(int i=len-3; i>=0; i--) for(int j=i+2; j<len; j++) isPal[i][j]=(s[i]==s[j])&&isPal[i+1][j-1]; //求最小切割 vector<int> minCuts(len, 0); //记录以i结尾的子串的最小切分数 for(int i=0; i<len; i++){ int mincut=INT_MAX; for(int j=-1; j<i; j++){ if(isPal[j+1][i]){ if(j==-1)mincut=0; else if(minCuts[j]+1<mincut)mincut=minCuts[j]+1; } } if(mincut!=INT_MAX)minCuts[i]=mincut; } return minCuts[len-1]; }};
0 0
- LeetCode: Palindrome Partitioning II [132]
- LeetCode 132 Palindrome Partitioning II
- Leetcode(132) Palindrome Partitioning II
- [leetcode 132] Palindrome Partitioning II
- leetcode || 132、Palindrome Partitioning II
- leetcode 132: Palindrome Partitioning II
- 132 Palindrome Partitioning II [Leetcode]
- LeetCode #132: Palindrome Partitioning II
- Leetcode 132 Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- java数据库连接
- 二分类问题特征选择的常用两个方法
- linux下appach服务器禁止ip访问
- 数据库基础
- SGU 403
- LeetCode: Palindrome Partitioning II [132]
- 左右鼠标响应
- java通过JDBC链接SQLServer2012
- 前端学习-jquery-实现点击button对文本的add及detele
- 第二章 查看数据
- openCV直方图相关函数
- 如何在Cocos2d-x游戏里集成iAd广告
- 前端学习——选择结果为JQuery对象还是DOM对象?
- hdu 1023 Train Problem II(catalan 大数)uva 10303 uva 991