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
  • 相关阅读:
    前端万字面经——进阶篇
    canvas 爬坑路【属性篇】
    Linux下提权反弹脚本
    修改和重置WAMP的phpMyAdmin密码
    如何调试Apache的URL重写(转载收藏)
    sharepoint 计算列的公式
    SharePoint控件的使用
    快速查看dll的PublicToken。
    DataCogsFieldControls 有时保存不上的问题
    遍历文件中的资源
  • 原文地址:https://www.cnblogs.com/freeneng/p/3247967.html
Copyright © 2011-2022 走看看