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

    Example:

    Input: "aab"
    Output:
    [
      ["aa","b"],
      ["a","a","b"]
    ]
    
     

    Approach #1: backtracking. [C++]

    class Solution {
    public:
        vector<vector<string>> partition(string s) {
            vector<vector<string>> ans;
            if (s.length() == 0) return ans;
            
            vector<string> path;
            dfs(s, 0, ans, path);
            
            return ans;
        }
        
    private:
        void dfs(const string s, int idx, vector<vector<string>>& ans, vector<string>& path) {
            if (s.length() == idx) {
                ans.push_back(path);
                return;
            }
            
            for (int i = idx; i < s.length(); ++i) {
                if (isPalindrome(s, idx, i)) {
                    path.push_back(s.substr(idx, i-idx+1));
                    // this is the point code in this problem.
                    dfs(s, i+1, ans, path);
                    path.pop_back();
                }
            }
        }
        
        bool isPalindrome(const string s, int start, int end) {
            while (start <= end) {
                if (s[start++] != s[end--])
                    return false;
            }
            
            return true;
        }
    };
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Redis系统管理
    Redis简介和安装
    在Azure中搭建Ghost博客并绑定自定义域名和HTTPS
    ML:单变量线性回归(Linear Regression With One Variable)
    PRML Chapter4
    Windows+Idea安装Hadoop开发环境
    包装类
    认识J2SE
    Spark基本原理
    SQL总结
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10353303.html
Copyright © 2011-2022 走看看