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

[leetcode-131-Palindrome Partitioning]

时间:2017-06-14 18:14:16      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:ever   判断   div   string   cto   etc   eve   bsp   bst   

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

思路:

回溯法。注意随时判断子字符串是否是回文串。

     bool isPali(string s)
     {
         int len = s.length();        
         for (int i = 0; i <= s.length()/2;i++)
         {
             if (s[i] != s[len - i - 1])return false;
         }
         return true;
     }
     void parti(vector<vector<string>>& res, vector<string>& pal,string s,int begin)
     {
         if (begin>=s.length())
         {
             res.push_back(pal);
             return;
         }
         for (int i = begin; i < s.length();i++)
         {
             if (isPali(s.substr(begin,i-begin+1)))
             {
                 pal.push_back(s.substr(begin, i - begin + 1));// pal.push_back(s.substr(i, i - begin + 1));这样不对
                 parti(res, pal, s, i + 1);
                 pal.pop_back();
             }
         }
     }
     vector<vector<string>> partition(string s)
     {
         vector<vector<string>> res;
         if (s.empty())return res;
         vector<string> pal;
         parti(res, pal, s, 0);
         return res;
     }

 

[leetcode-131-Palindrome Partitioning]

标签:ever   判断   div   string   cto   etc   eve   bsp   bst   

原文地址:http://www.cnblogs.com/hellowooorld/p/7009889.html

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