首页 > 其他 > 详细

LeetCode - Palindrome Partitioning II

时间:2014-02-27 21:23:47      阅读:501      评论:0      收藏:0      [点我收藏+]

Palindrome Partitioning II

2014.2.26 22:57

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.

Solution:

  This problem can be solved with dynamic programming. First check if every segment is palindromic, then do the DP.

  The idea is explained in the code comment, please see for yourself.

  Total time and space complexities are both O(n^2).

Accepted code:

bubuko.com,布布扣
 1 // 1WA, 1AC, O(n^2) solution with DP
 2 #include <string>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     int minCut(string s) {
 8         int **pal = nullptr;
 9         int *dp = nullptr;
10         int len = (int)s.size();
11         
12         if (len <= 1) {
13             return 0;
14         }
15         
16         pal = new int*[len];
17         dp = new int[len + 1];
18         
19         int i, j;
20         for (i = 0; i < len; ++i) {
21             pal[i] = new int[len];
22         }
23         for (i = 0; i < len; ++i) {
24             for (j = 0; j < len; ++j) {
25                 pal[i][j] = 0;
26             }
27         }
28         
29         // pal[i][j] means whether the substring s[i:j] is a palindrome.
30         for (i = 0; i < len; ++i) {
31             pal[i][i] = 1;
32         }
33         for (i = 0; i < len - 1; ++i) {
34             pal[i][i + 1] = (s[i] == s[i + 1]) ? 1 : 0;
35         }
36         for (i = 2; i <= len - 1; ++i) {
37             for (j = 0; j + i < len; ++j) {
38                 pal[j][j + i] = (pal[j + 1][j + i - 1] && (s[j] == s[j + i])) ? 1 : 0;
39             }
40         }
41         
42         // dp[i] means the minimal number of segments the substring s[0:i] 
43         // must be cut, so that they‘re all palindromes.
44         dp[0] = 0;
45         for (i = 1; i <= len; ++i) {
46             dp[i] = i;
47             for (j = 0; j < i; ++j) {
48                 if (pal[j][i - 1]) {
49                     dp[i] = mymin(dp[j] + 1, dp[i]);
50                 }
51             }
52         }
53         
54         int ans = dp[len];
55         for (i = 0; i < len; ++i) {
56             delete[] pal[i];
57         }
58         delete[] pal;
59         delete[] dp;
60         
61         return ans - 1;
62     }
63 private:
64     int mymin(const int x, const int y) {
65         return (x < y ? x : y);
66     }
67 };
bubuko.com,布布扣

LeetCode - Palindrome Partitioning II,布布扣,bubuko.com

LeetCode - Palindrome Partitioning II

原文:http://www.cnblogs.com/zhuli19901106/p/3570461.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!