zoukankan      html  css  js  c++  java
  • [LintCode] Palindrome Partitioning II

    Given a string s, cut s into some substrings such that every substring is a palindrome.

    Return the minimum cuts needed for a palindrome partitioning of s.

     
    Example

    For example, given s = "aab",

    Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

    Sol:

    class Solution {
    public:
        /**
         * @param s a string
         * @return an integer
         */
        int minCut(string s) {
             int n = s.size();
            vector<vector<bool> > isPalin(n, vector<bool>(n, false));
            vector<int> min_cut(n, -1); //min cut to end
            
            for(int i = 0;i < n;++i)
                isPalin[i][i] = true;
            
            min_cut[0] = 0;
            for(int i = 1;i < n;++i){
                min_cut[i] = min_cut[i - 1] + 1;
                for(int j = 0;j < i;++j){
                    if(s[j] == s[i]){
                        if(j + 1 == i || isPalin[j + 1][i - 1]){
                            isPalin[j][i] = true;
                            if(j > 0) min_cut[i] = min(min_cut[i], min_cut[j - 1] + 1);
                            else min_cut[i] = 0;
                        }
                    }
                }
            }
            
            return min_cut[n - 1];
        }
    };
  • 相关阅读:
    参考__JAVA
    债券价格和通胀率
    C++ 面试题
    欧式和美式期权
    explicit
    smart pointer
    const pointer
    manacher-马拉车算法
    输入有空格的字符串的2种方法
    bind()与connect()——计网中socket的使用
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/4863141.html
Copyright © 2011-2022 走看看