Palindrome Partitioning II
来源:互联网 发布:淘宝客现状 编辑:程序博客网 时间:2024/06/16 18:48
Given a string s,partition s such that every substring of the partition is apalindrome.
Return the minimumcuts 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来做,matrix[i][j]表示i到j是否为回文。同时更新每个位置上的最小cuts个数。用i和j两个变量来控制循环,i从elementNum-1->0, i--; j从=i到elementNum,j++.这样的双指针循环也类似于DFS。
class Solution {public: int minCut(string s) { if (s.size() == 0) { return -1; } int elementNum = s.size(); // matrix[i][j]表示从i到j是否为回文 vector< vector<bool> > matrix(elementNum, vector<bool> (elementNum, false)); vector<int> cuts(elementNum + 1, 0); //cuts[i]表示从i到结尾(elementNum-1)的最小切割数, 注意cuts的size比elementNum还多一个,是因为后面有一个i初始值为elementNum-1的时候要算一个cuts[j+1], j=i; //初始值为最差情况,即从i到结尾每个位置都得单独切割,即每个字母是单独的回文 for (int i = 0; i < elementNum; i++) { cuts[i] = elementNum - i; } for (int i = elementNum - 1; i >= 0 ;i--) { for (int j = i; j < elementNum; j++) { //为回文的情况 if ((j - i < 2 || matrix[i+1][j-1]) && s[i] == s[j]) { matrix[i][j] = true; cuts[i] = min(cuts[i], cuts[j + 1] + 1); } } } return cuts[0] - 1; //减1是因为|a|b|c,a前面也算一个cut }};
0 0
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- Palindrome Partitioning II
- Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- Palindrome Partitioning II
- LetCode:Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- Gas Station
- Jdk1.7环境变量的配置
- poj3278 Catch That Cow(BFS)
- 网页任意浮动广告
- 结构体(struct)的使用、内存分布以及字节对齐测试总结
- Palindrome Partitioning II
- 猜图项目全部代码
- Android 官网教程
- js中浮点型是如何运算
- Longest Palindromic Substring
- zoj 1151 Word Reversal
- 【总结】IE和Firefox的Javascript兼容性总结
- HDU2523(论scanf的重要性)
- ios 归档解归档