LeetCode —— Palindrome Partition II
来源:互联网 发布:java年终总结 编辑:程序博客网 时间:2024/05/18 00:00
链接:http://leetcode.com/onlinejudge#question_132
原题:Palindrome Partitioning II
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长度为i的子串s[0~i-1]最少的分割段数为minSegs[i],那么最小的cut数就是minSegs[i]-1,显然minSegs[0] = 0, minSegs[1] = 1。
先在考虑字符s[i]加入改子串中,只有两种情况:
1)直接在s[i-1]和s[i]之间切一刀,那么 所得的段数为minSegs[i] + 1
2)和子串s[0~i-1]分段的最后一段合并为一个新回文串(如果可以合并的话),记最后一段的长度为length,那么所得段数为
minSegs[i-1-length] +1。现在考虑s[0~i-1]分段的最后一段,显然这一段是一个回文串,所以我们要记录以s[i-1]结尾的
所有回文串长度,那么只要检查 s[i-1-length] == s[i],就可以并上s[i]形成新的子串。
所以整个时间复杂度是O(n^2)
class Solution {public: int minCut(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.size() < 2) return 0; int length = s.size(); int *minSegs = new int[length+1]; minSegs[0] = 0; minSegs[1] = 1; int **dp = new int*[2]; dp[0] = new int[length+2]; dp[1] = new int[length+2]; dp[0][0] = dp[1][0] = 0; dp[0][1] = dp[1][1] = 1; dp[0][2] = -1; int cur = 0; int pre = 1; for (int i=1; i<s.size(); i++) { int cur = i % 2; int pre = (i +1) % 2; minSegs[i+1] = minSegs[i] + 1; int n = 1; for (int j=0; dp[pre][j] != -1; j++) { int left = i-1-dp[pre][j]; if (left>=0 && s[left]==s[i]) { dp[cur][++n] = dp[pre][j] + 2; if (minSegs[left] + 1 < minSegs[i+1]) minSegs[i+1] = minSegs[left] + 1; } } dp[cur][++n] = -1; } int min = minSegs[s.size()] - 1; delete []minSegs; return min; }};
- LeetCode —— Palindrome Partition II
- leetcode palindrome partition II
- LeetCode——Palindrome Partition
- palindrome partition II
- palindrome-partition-ii
- LeetCode——Palindrome Partitioning II
- leetcode——Palindrome Partitioning II
- leetcode 132 —— Palindrome Partitioning II
- LeetCode 131: Palindrome Partition
- [LeetCode] Palindrome Partition
- [LeetCode] Palindrome Partition [11]
- LeetCode: Palindrome Partition
- [LeetCode] 064: Palindrome Partition
- leetcode——132—— Palindrome Partitioning II
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- eclipse在HTC Desire V上真机调试运行Android程序
- 【TCP/IP学习笔记1】 &C语言讲解
- Feathers组件--之--列表
- 享元模式
- 数据结构学习整理目录
- LeetCode —— Palindrome Partition II
- 由KMP算法谈到BM算法
- TCP/IP学习系列》1》简单讲解
- Linux中的后台运行
- 实现并验证单列模式
- 13.4.7周赛解题报告
- 项目3
- Java设计模式之一(简单工厂模式)
- 2013编程之美-传话游戏