随笔- 509  文章- 0  评论- 151  阅读- 22万 

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:

复制代码
 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 };
复制代码

 

 posted on   zhuli19901106  阅读(213)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示