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

题意:将字符串拆分回文串,并输出每一种情况。

思路:采用DFS的方法,但我对这个用法不是很熟,所以又找思路了,然后自己按照自己理解的写出。终止条件是: 每次按各种分法遍历完字符串以后就将满足的情况输出到结果中。这题是典型的深搜模式,判断后回溯。参考1Grandyang

 1 class Solution {
 2 public:
 3     vector<vector<string>> partition(string s) 
 4     {
 5         vector<vector<string>> res;
 6         vector<string> path;
 7         if(s.size()<=0) return res;
 8         int len=s.size();
 9 
10         subParti(s,len,0,path,res);
11         return res;    
12     }
13 
14     void subParti(string s,int len,int star,vector<string> &path,vector<vector<string>> &res)
15     {
16         if(star==len)
17         {
18             res.push_back(path);
19             return;
20         }
21             
22         string str;
23         
24         for(int i=star;i<len;++i)
25         {
26             str=s.substr(star,i-star+1);
27 
28             if(isPalindrome(str))
29             {
30                 path.push_back(str);
31                 subParti(str,len,i+1,path,res);
32                 path.pop_back();
33             }
34         }
35     }
36 
37     //判断是否为回文串
38     bool isPalindrome(string str)
39     {
40         int strLen=str.size();
41         if(strLen==0)
42             return false;
43         
44         int left=0,right=strLen-1;
45         while(left<right)
46         {
47             if(str[left] !=str[right])
48                 return false;
49             
50             left++;
51             right--;
52         }
53         return true;
54     }
55 
56 };

 

posted @ 2017-06-28 00:55  王大咩的图书馆  阅读(495)  评论(1编辑  收藏  举报