zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    Segmentation fault (core dumped)
    Missing separate debuginfos, use: debuginfo-install
    Qt学习资源
    Qt学习过程中遇到的问题
    深入浅出MFC--第一章
    MVC – 3.EF(Entity Framework)
    MVC基础知识 – 2.新语法
    js获取url参数值(HTML之间传值)
    解决IIS7、IIS7.5中时间格式显示的问题
    web.config详解 -- asp.net夜话之十一
  • 原文地址:https://www.cnblogs.com/freeneng/p/3247967.html
Copyright © 2011-2022 走看看