【C++】LeetCode 132. Palindrome Partitioning II
来源:互联网 发布:sql delete多个表 编辑:程序博客网 时间:2024/05/21 21:33
题目:
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.
解析:
这题有两种方法:
1、构造一个二维数组flag,判断是否为回文,然后用动态规划计算最小cut,但是时间比较长
2、把方法一中两个过程融合到一起
方法一:
class Solution {public: int minCut(string s) { int len=s.size(); vector<vector<int>> flag(len,vector<int>(len)); for(int i=0;i<len;i++) { for(int k=0,j=i;j<len;j++,k++) { if((k==j)||((s[k]==s[j])&&(k==j-1||flag[k+1][j-1]))) flag[k][j]=1; else flag[k][j]=0; } } vector<int> cut(len,len); for(int i=0;i<len;i++) { for(int j=0;j<=i;j++) { if(flag[j][i]) { if(j==0)cut[i]=0; else cut[i]=cut[i]>cut[j-1]+1?cut[j-1]+1:cut[i]; } } } return cut[len-1]; }};
方法二:
class Solution {public: int minCut(string s) { int len=s.size(); vector<vector<int>> flag(len,vector<int>(len)); vector<int> cut(len,len); for(int i=len-1;i>=0;i--) { for(int j=i;j<len;j++) { if((i==j)||((s[i]==s[j])&&(i==j-1||flag[i+1][j-1]))) { flag[i][j]=1; if(j==len-1) cut[i]=0; else cut[i]=min(cut[i],cut[j+1]+1); } else flag[i][j]=0; } } return cut[0]; }};
0 0
- LeetCode 132. Palindrome Partitioning II (C++)
- 【C++】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
- 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】132.Palindrome Partitioning II
- Leetcode 132. Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II
- leetcode 132. Palindrome Partitioning II
- 汇编程序:简单的菜单
- Android高手进阶教程(三)之----Android 中自定义View的应用.
- solr之commit和softcommit
- 一个web应用的诞生(3)
- COMPUTER NETWORK
- 【C++】LeetCode 132. Palindrome Partitioning II
- python开发技能表格
- 犀牛软件rhinoceros的参数化设计插件草蜢grasshopper的安装
- Java基础-线程的通信
- FILE结构体(文件描述符及缓冲区)
- CTreeCtrl使用演示
- 数学实验:Matlab代码 用动画展示一拱摆线的构造过程
- matlab-模糊控制-WM算法
- kruskal最小生成树问题