码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Palindrome Partitioning

时间:2014-07-18 12:12:12      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   art   io   

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 

 1 class Solution {
 2     private:
 3             vector<vector<string> >   m_res;
 4     public:
 5         vector<vector<string> > partition(string s)
 6         {
 7             size_t size = s.size();
 8             if(size == 0)
 9                 return m_res;
10 
11             vector<string> str;
12             dfs(s, 0, size - 1, str);
13             return m_res;
14         }
15 
16         void dfs(string s, size_t begin, size_t end, vector<string>& str)
17         {
18             if(begin > end)
19             {
20                 m_res.push_back(str);
21                 return;
22             }
23 
24             for(size_t i = begin; i<=  end; i++)
25             {
26                 if(isPalindrome(s, begin, i))
27                 {
28                     str.push_back(s.substr(begin, i-begin + 1));
29                     dfs(s, i+1, end, str);
30                     str.pop_back();
31                 }
32             }
33         }
34 
35         bool isPalindrome(string s, size_t begin, size_t end)
36         {
37             if(begin == end)
38                 return true;
39             while(begin <= end)
40             {
41                 if(s[begin] == s[end])
42                 {
43                     begin++;
44                     end --;
45                 }
46                 else
47                     return false;
48             }
49             return true;
50         }
51 };

[LeetCode] Palindrome Partitioning,布布扣,bubuko.com

[LeetCode] Palindrome Partitioning

标签:style   blog   color   os   art   io   

原文地址:http://www.cnblogs.com/diegodu/p/3853066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!