LeetCode132. Palindrome Partitioning II

版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/87945920

132. Palindrome Partitioning II

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.

Example:

Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

题目:给定一个字符串s,通过合理的分隔使得字符串的每部分均为回文子串,返回所需的最少分隔次数。

思路:动态规划,参见解析。用cut[i]表示s中的s[...i-1]子字符串所需要的最小分隔次数,使得s[...i-1]中分隔后的子串均为回文串。对于字符串s中的每个字符,记为s[i],以s[i]为回文中心,如果s[i-1]=s[i+1],那么就可以更新s[...i+1]字符串的对应的最少分隔次数cut[i+1+1]cut[i+1+1] = min(cut[i+1+1], 1+cut[i-1]),子式1+cut[i-1]是因为s[i-1..i+1]已经为回文。将上述的外扩范围不断扩大,直到s[i-j...i+j]已经不是回文串则退出循环。同样考虑回文中心为偶数的情况。

工程代码下载

class Solution {
public:
    int minCut(string s) {
        int n = s.size();
        vector<int> cut(n+1);
        for(int i = 0; i < n+1; ++i)
            cut[i] = i - 1;

        for(int i = 0; i < n; ++i){
            //对于回文中心为奇数的情况
            for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j]; ++j)
                cut[i+j+1] = min(cut[i+j+1], 1 + cut[i-j]);
            //对于回文中心为偶数的情况
            for(int j = 1; i-j+1 >= 0 && i+j < n && s[i-j+1] == s[i+j]; ++j)
                cut[i+j+1] = min(cut[i+j+1], 1 + cut[i-j+1]);
        }
        return cut[n];
    }
};

猜你喜欢

转载自blog.csdn.net/grllery/article/details/87945920