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

 1 class Solution {
 2 public:
 3     int minCut(string s) {
 4         int N = s.size();
 5         bool isP[N];
 6         int dp[N];
 7         dp[0] = 0;
 8         for(int i = 1; i < N; ++i) {
 9             isP[i] = true;
10             dp[i] = dp[i-1] + 1;
11             for(int j = 0; j < i; ++j) {
12                 isP[j] = (s[i] == s[j]) ? isP[j+1] : false; // isP[j] == true   -> [j...i] is a palindrome
13                                                             // isP[j+1] == true -> [j+1...i-1] is a palindrome
14                 if (isP[j])
15                     dp[i] = (j == 0) ? 0 : min(dp[i], dp[j-1] + 1);  // dp[i] -> minCount for [0...i]
16             }
17         }
18         return dp[N-1];
19     }
20 };

 

the palindrome partitioning ["aa","b"] could be produced using 1 cut.

Solution: dp. Contributed by 孙冕. Great job:)

posted @ 2014-04-24 08:41  beehard  阅读(149)  评论(0编辑  收藏  举报