LeetCode 132. 分割回文串 II(Palindrome Partitioning II)

题目描述

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回符合要求的最少分割次数。

示例:

输入: "aab"
输出: 1
解释: 进行一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。

解题思路

动态规划思想。从最后一个字符开始向前遍历,每次判断以当前字符为首字母依次到最后字符的子字符串是否为回文串,若是则更新包含当前回文串的最小回文串数。具体想法可参考leetcode之 Palindrome Partitioning I&II

代码

 1 class Solution {
 2 public:
 3     int minCut(string s) {
 4         vector<vector<int>> dp(s.length(), vector<int>(s.length(), 0));
 5         vector<int> cnt(s.length() + 1, 0);
 6         for(int i = s.length() - 1; i >= 0; i--){
 7             cnt[i] = INT_MAX;
 8             for(int j = i; j < s.length(); j++){
 9                 if(s[i] == s[j] && (j - i <= 2 || dp[i + 1][j - 1])){
10                     dp[i][j] = 1;
11                     cnt[i] = min(cnt[i], cnt[j + 1] + 1);
12                 }
13             }
14         }
15         return cnt[0] - 1;
16     }
17 };

猜你喜欢

转载自www.cnblogs.com/wmx24/p/9885385.html