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

132 Palindrome Partitioning II 分割回文串 II

回文 回文串 tco ++ ali 例如 post 字符 code

給定一個字符串 s,將 s 分割成一些子串,使每個子串都是回文串。
返回 s 符合要求的的最少分割次數。
例如,給出 s = "aab",
返回 1 因為進行一次分割可以將字符串 s 分割成 ["aa","b"] 這樣兩個回文子串。
詳見:https://leetcode.com/problems/palindrome-partitioning-ii/description/

class Solution {
public:
    int minCut(string s) {
        int len = s.size();
        int dp[len + 1];
        for (int i = 0; i <= len; ++i)
        {
            dp[i] = len - i - 1;
        }
        vector<vector<bool>> isP(len,vector<bool>(len,false));
        for (int i = len - 1; i >= 0; --i) 
        {
            for (int j = i; j < len; ++j) 
            {
                if (s[i] == s[j] && (j - i <= 1 || isP[i + 1][j - 1]))
                {
                    isP[i][j] = true;
                    dp[i] = min(dp[i], dp[j + 1] + 1);
                }
            }
        }
        return dp[0];
    }
};

參考:https://www.cnblogs.com/springfor/p/3891896.html

132 Palindrome Partitioning II 分割回文串 II