Monday, May 18, 2015

Palindrome Partitioning I

来源:Leetcode

原帖:https://oj.leetcode.com/problems/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"]
 ]

代码:
 class Solution {  
 public:  
   bool isPalindrome(const string &s) {  
     int i = 0, j = s.size()-1;  
     while (i < j) {  
       if (s[i] != s[j]) return false;  
       i++; j--;  
     }  
     return true;  
   }  
   
   void partitionHelper(const string &s, int start, vector<string> &path, vector<vector<string> >& res) {  
     if (start == s.size()) {  
       res.push_back(path);  
       return;  
     }  
     string palindrom;  
     for (int i = start; i < s.size(); ++i) {  
       palindrom.push_back(s[i]);  
       if (isPalindrome(palindrom)) {  
         path.push_back(palindrom);  
         partitionHelper(s, i + 1, path, res);  
         path.pop_back();           
       }  
     }  
   }  
   
   vector<vector<string>> partition(string s) {  
     vector<string> path;  
     vector<vector<string> > res;  
     partitionHelper(s, 0, path, res);  
     return res;  
   }  
 };  


No comments:

Post a Comment