1. 程式人生 > >LeetCode 132. 分割回文串 II(Palindrome Partitioning II)

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 };