zoukankan      html  css  js  c++  java
  • 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.

    For example, given s = "aab",
    Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

    Solution:

    Compare with 131. Palindrome Partitioning, this is a DP problem. In order to pass the OJ, there are two DP, the first one is the initialization of the table, it records if from i to j is a palindrome.

    class Solution {
    public:
        int minCut(string s) {
            if(s.empty()){
                return 0;
            }
            int size = s.size();
            // size * size table
            // i to j is a palindrome or not
            vector<vector<bool>> table(size, vector<bool>(size, false));
            initialize(table, s);
            vector<int> dp(size + 1);
            for(int i = 0; i <= size; i++){
                dp[i] = i - 1;
            }
            for(int i = 1; i <= size; i++){
                for(int j = 0; j < i; j++){
                    if(table[j][i - 1]){
                        dp[i] = min(dp[i], dp[j] + 1);
                    }
                }
            }
            return dp[size];
        }
    private:
        void initialize(vector<vector<bool>>& table, string s){
            for(int i = 0; i < s.size(); i++){
                table[i][i] = true;
            }
            for(int i = 0; i < s.size() - 1; i++){
                table[i][i + 1] = s[i] == s[i + 1];
            }
            for(int i = s.size() - 1; i >= 0; i--){
                for(int j = i + 2; j < s.size(); j++){
                    table[i][j] = table[i + 1][j - 1] && s[i] == s[j];
                }
            }
            return;
        }
    };
  • 相关阅读:
    台式机+笔记本的扩展模式+远程登录设置
    Hadoop 集群搭建以及脚本撰写
    Python 入门学习(三)
    1056 Mice and Rice
    1057 Stack
    1058 A+B in Hogwarts
    1059 Prime Factors
    使用熔断器仪表盘监控
    使用熔断器防止服务雪崩
    创建服务消费者(Feign)
  • 原文地址:https://www.cnblogs.com/wdw828/p/6834704.html
Copyright © 2011-2022 走看看