LeetCode Palindrome Partitioning II(***)
来源:互联网 发布:富途证券 知乎 编辑:程序博客网 时间:2024/05/17 22:38
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 ofs.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
首先,遍历s,求出所有的回文,存放在二维数组中,对于flag[i][j],如果s[i..j]为回文,则flag[i][j]=1,否则flag[i][j]=0;
然后,对于最小的剪切次数,可以通过DP思想,从s[0]开始往s[s.length()-1],求最小的剪切次数f[0]...f[s.length()-1]。
时间复杂度为O(n^2)。
备注:对于a+b=c?1:2,与a+(b=c?1:2)是不相同的!
class Solution {public: vector<vector<int> > flag; void buildFlag(string s){ vector<int> temp; for(int i=0;i<s.length();i++)temp.push_back(0); for(int i=0;i<s.length();i++)flag.push_back(temp); for(int i=0;i<s.length();i++){ int tempi=i,tempj=i; while(tempi>=0&&tempj<s.length()&&s[tempi]==s[tempj]){flag[tempi][tempj]=1;tempi--;tempj++;} tempi=i;tempj=i+1; while(tempi>=0&&tempj<s.length()&&s[tempi]==s[tempj]){flag[tempi][tempj]=1;tempi--;tempj++;} } } int minCut(string s) { if(s.length()<=1)return 0; buildFlag(s); int *f = new int[s.length()]; f[0]=0; for(int i=1;i<s.length();i++){ f[i]=f[i-1]+1; if(flag[0][i])f[i]=0; else { for(int j=0;j<i;j++) f[i]=min(f[i],f[j]+(flag[j+1][i]==1?1:(i-j)));//如果用==?:,一定要注意运算符的优先级 } } return f[s.length()-1]; }};
0 0
- 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
- 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
- [LeetCode] Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- 下载文件时文件名与弹出框乱码
- 静态变量和实例变量到底有什么区别
- hdu4525威威猫系列故事——吃鸡腿
- leetcode Insertion Sort List
- Qt 如何实现的 Meta Object
- LeetCode Palindrome Partitioning II(***)
- 记忆中的世界杯
- 单片机系统与标准PC键盘的接口模块设计
- MIT一牛人对数学在机器学习中的作用给的评述
- 奋斗吧之“和loser对话”小故事
- .Net之路(十四)com组件、OLEDB导入EXCEL
- java实现"烟花燃放"案例
- 排序总结之冒泡排序
- MongoDB在RHEL6.5下的安装