码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Partitioning II

时间:2014-08-13 12:45:46      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   for   ar   art   

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确定s中任意两个字符之间是否构成回文。若isPalindrome[step][i]为true,则表示str.substr(i,step+i)构成回文。

        然后使用一个两层的循环查找出最小划分数。

 1 class Solution {
 2 public:
 3     int minCut( string s ) {
 4         int size = s.length();
 5         if( size <= 1 ) { return 0; }
 6         vector<bool> *isPalindrome = new vector<bool>[size];
 7         isPalindrome[0].resize( size, true );
 8         for( int step = 1; step < size; ++step ) {
 9             isPalindrome[step].resize( size-step, false );
10             if( step == 1 ) {
11                 for( int i = 0; i < size-1; ++i ) {
12                     if( s[i] == s[i+1] ) { isPalindrome[1][i] = true; }
13                 }
14             } else {
15                 for( int i = 0; i < size-step; ++i ) {
16                     if( s[i] == s[i+step] && isPalindrome[step-2][i+1] ) { isPalindrome[step][i] = true; }
17                 }
18             }
19         }
20         vector<int> Q( size, 0 );
21         for( int i = 1; i < size; ++i ) {
22             if( isPalindrome[i][0] ) { continue; }
23             Q[i] = Q[i-1]+1;
24             for( int j = i-1; j > 0; --j ) {
25                 if( isPalindrome[i-j][j] && Q[i] > Q[j-1]+1 ) {
26                     Q[i] = Q[j-1]+1;
27                     if( Q[i] == 1 ) { break; }
28                 }
29             }
30         }
31         delete [] isPalindrome;
32         return Q.back();
33     }
34 };

 

Palindrome Partitioning II,布布扣,bubuko.com

Palindrome Partitioning II

标签:style   blog   color   使用   io   for   ar   art   

原文地址:http://www.cnblogs.com/moderate-fish/p/3908624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!