Palindrome Partitioning II(找给定字符串分割次数获取回文字串, 动态规划)
2013-07-23 01:21
411 查看
/*** Palindrome Partitioning IIMar 19518 / 34344 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. 题目大意:给出一个字符串,求出最小分割次数,使得分割出来的字符串是回文 思路:动态规划。从后面开始往前遍历,从字串起点i开始到j的字串为回文,那么 就分为两种情况:1、i-j为一段 2、i-j不为一段,两种情况取分割较少的为 dp[i] = min(dp[i], dp[j+1] + 1) */ #include <iostream> #include <stdlib.h> #include <string> using namespace std; int minCut(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int length = s.size(); int dp[length+1]; bool isPalin[length][length]; //首先初始化dp数组,长度为length时,最小分割次数为0,长度为0时,分割次数为length-1 for(int i=0; i<=length; i++) dp[i] = length - i; //isPalin[i][j] 表示从i到j之间的子串是否回文 for(int i=0; i<length; i++) for(int j=0; j<length; j++) isPalin[i][j] = false; for(int i=length-1; i>=0; i--){ for(int j=i; j<length; j++){ //如果子串i-j的头尾相同,如果此时子串长度为2或除掉头尾i和j的字串也是回文,那么该i-j的串也是回文 if(s[i] == s[j] && (j - i <= 1 || isPalin[i+1][j-1])){ isPalin[i][j] = true; dp[i] = min(dp[i], dp[j+1] + 1); //比较当前回文串i-j与i-j之后的j起始点比较,取小的一个 } } } return dp[0]-1; } int main() { string s ; cin >> s; cout << minCut(s) << endl; system("pause"); return 0; }
相关文章推荐
- 分割成回文需要的最小分割数 Palindrome Partitioning II @LeetCode
- 19. Palindrome Partitioning && Palindrome Partitioning II (回文分割)
- 最小回文分割数 Palindrome Partitioning II
- Palindrome Partitioning&II(回文字符串)
- LeetCode-Palindrome Partitioning II-回文分割-DP优化
- [LeetCode]—Palindrome Partitioning II 回文分割,求最小分割数
- [LeetCode 132] - 回文分割II(Palindrome Partitioning II)
- LeetCode 132. Palindrome Partitioning II(回文切分)
- 每日AC-LeetCode-palindrome-partitioning-ii --动态规划
- LeetCode | Palindrome Partitioning II(最少切割次数将一个子串划分成回文子串)
- palindrome-partitioning I&II——回文切割、深度遍历
- 132. Palindrome Partitioning II (动态规划)
- LeetCode 132 Palindrome Partitioning II (动态规划)
- java中用正则表达式获取一个指定的子字符在字符串中出现的指定次数的下标索引,并且进行字符串分割
- 变成回文字符串所需要的次数-动态规划
- LeetCode 之 Palindrome Partitioning II(动态规划)
- 给定字符串S,是的每个子串为回文子串,求最小划分次数
- Palindrome Partitioning I 和II的代码和理解(动态规划思想)
- String去除字符串两端空格、将一个字符串进行反转、计算字符串中出现的的次数、获取两个字符串中最大相同字串
- 动态规划——回文最小分割数(palindrome-partitioning-ii)