• [Leetcode 104] 131 Palindrome Partitioning


    Problem:

    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"]
      ]

    Analysis:

    At first glance, it seems very hard. But it's a DFS problem. What is the possible choice? A substring is a possible if it's a palindrom. Then if the substring is valid, then we can recursivly call the solve on the remaining substring to continue generate palindrom until the current position is greater or equal than the total string's length.

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<string> > res;
     4     vector<string> tmp;
     5 
     6     vector<vector<string>> partition(string s) {
     7         // Start typing your C/C++ solution below
     8         // DO NOT write int main() function
     9         res.clear();
    10         tmp.clear();
    11 
    12         if (s == "") return res;
    13 
    14         solve(s, 0);
    15         
    16         return res;
    17     }
    18 
    19 private:
    20     bool solve(string s, int p) {
    21         if (p >= s.length()) {
    22             res.push_back(tmp);
    23             return true;
    24         }
    25 
    26         int lmt = s.length() - p;
    27         for (int l=1; l <= lmt; l++) {
    28             string st = s.substr(p, l);
    29             
    30             if (isPalindrom(st)) {
    31                 tmp.push_back(st);
    32                 solve(s, p+l);
    33                 tmp.pop_back();
    34             }
    35         }
    36 
    37         return false;
    38     }
    39     
    40     bool isPalindrom(string s) {
    41         int i=0, j=s.length()-1;
    42         
    43         while (i < j) { 
    44             if(s[i++] != s[j--])
    45                 return false;
    46         }
    47         
    48         return true;
    49     }
    50 };
    View Code
  • 相关阅读:
    Spring基于纯注解的声明式事务控制
    Spring基于XML的声明式事务控制
    2.Jersey
    1.解读REST和JAX-RS
    getHibernateTemplate和getSession 区别, this.getHibernateTemplate().getSessionFactory().getCurrentSession()和OpenSession区别
    eclipse安装maven报错
    MyEclipse10 + tomcat8 64位
    理解MVC
    java编程规范
    c3p0详细配置
  • 原文地址:https://www.cnblogs.com/freeneng/p/3247967.html
Copyright © 2020-2023  润新知