LeetCode 132. Palindrome Partitioning II
来源:互联网 发布:win7电脑摄像头软件 编辑:程序博客网 时间:2024/05/22 03: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.
题目分析:给出一个字符串,将该字符串分割,使得每部分都是回文串,求最小的额切割次数。
假设dp[i][j]表示s[i…j]的最小切割次数,则有
代码如下:
class Solution {public: int minCut(string s) { int n = s.length(); int dp[n][n]; memset(dp,0,sizeof(dp)); for(int i = 0; i < n - 1; i++) { if(s[i] == s[i+1]) dp[i][i+1] = 0; else dp[i][i+1] = 1; } for(int len = 2; len <= n; len++) { for(int i = 0; i + len < n; i++) { int j = i + len; dp[i][j] = n; if(s[i] == s[j] && dp[i+1][j-1] == 0) dp[i][j] = 0; for(int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + 1); } } } return dp[0][n-1]; }};
结果,超时了。后来看了大神的代码,增加了一个数组,只用了O(n^2)的复杂度。
代码如下:
class Solution {public: int minCut(string s) { int n = s.length(); bool isPal[n][n]; memset(isPal,0,sizeof(isPal)); int cut[n]; for(int j = 0; j < n; j++) { cut[j] = j; for(int i = 0; i <= j; i++) { if(s[i] == s[j] && (j - i <= 1 || isPal[i+1][j-1] == true) ) { isPal[i][j] = true; if(i > 0) { cut[j] = min(cut[j],cut[i-1] + 1); } else { cut[j] = 0; } } } } return cut[n-1]; }};
对于每个cut[j],同样是将[0…j]分成两部分,只不过,其中一部分是回文子串。
这道题和Leetcode 279. Perfect Squares的技巧很相似。
阅读全文
0 0
- 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
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- 交换两个变量的值,不使用第三个变量的四种方法
- 分析一段H264视频数据
- SpringMVC学习笔记(4)-----访问静态页面
- let's shell---Find 指令用法
- Node.js介绍
- LeetCode 132. Palindrome Partitioning II
- [ZJOI2006]物流运输 (最短路+dp)
- [SDUT](2121)数据结构实验之链表六:有序链表的建立
- Office转换技巧之转换pdf格式文件的方法分享
- codeforce 864C Bus(模拟)
- 【BZOJ 4569】【SCOI】【萌萌哒】【并查集】【倍增均摊优化】
- 【后缀数组】不可重叠最长重复子串
- Manthan, Codefest 17
- flume-ng+Hadoop实现日志收集