zoukankan      html  css  js  c++  java
  • 19. Palindrome Partitioning && Palindrome Partitioning II (回文分割)

    Palindrome Partitioning

    Given a string s, partition s such that every substring of the partition is a palindrome.

    Return all possible palindrome partitioning of s.

    For example, given s = "aab", Return

      [
        ["aa","b"],
        ["a","a","b"]
      ]

    思想: 简单的深度优先搜索。
    bool isPalindrome(string& s, int l, int r) {
        while(l++ < r--) 
            if(s[l] != s[r]) return false;
        return true;
    }
    class Solution {
    public:
        void dfs(string& s, vector<string>& vec2, size_t id) {
            if(id == s.size()) {
                vec.push_back(vec2);
                return;
            }
            for(int end = id; end < s.size(); ++end) {
                if(isPalindrome(s, id, end)) {
                    vec2.push_back(s.substr(id, end-id+1));
                    dfs(s, vec2, end+1);
                    vec2.pop_back();
                }
            }
        }
        vector<vector<string> > partition(string s) {
            if(s == "") return vec;
            vector<string> vec2;
            dfs(s, vec2, 0);
            return vec;
        }
    private:
        vector<vector<string> > vec;
    };
    

    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.

    思想: 动态规划:

    n = s.length();

    Record[i] =                                 0                                          , ( i = n || isPalindrome(i, n-1))

                       min(n-1-i, Record[k]+1 ( isPalindrome(i, k) ) )        , otherwise

    where i belong to interval [0, n].

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

  • 相关阅读:
    函数声明 函数表达式 通俗解释
    javascript 作用域 通俗解释
    webpack 实用配置总结
    webapck html-loader实现资源复用
    webpack css打包为一个css
    网站banner图片制作(简易版)
    webpack 通用模块(每个页面都用到的js)编译
    webpack CommonsChunkPlugin 提取公共代码
    SQL Server索引
    如何判断http服务器是否支持range寻址
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3933986.html
Copyright © 2011-2022 走看看