Saturday, March 9, 2013

Palindrome Partitioning

/*
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(string s){
      int size = s.length();
      int i = 0;
      int j = size-1;
      while(i<j){
        if(s[i]!=s[j]) return false;
        i++;
        j--;
      }
      return true;
    }
   
    vector<vector<string>> findPartition(string s, int pos){
      vector<string> line;
      vector<vector<string>> result;
      if(pos==0){
        line.push_back(s.substr(0,1));
        result.push_back(line);
        return result;
      }
     
      int i;
      result = findPartition(s, pos-1);
      int currectResultSize = result.size();
      for(i=0; i<currectResultSize; i++){
        result[i].push_back(s.substr(pos,1));
      }
     
      i = 0;
      string newString = s.substr(i, pos-i);
      int found = newString.find(s[pos]);
      vector<vector<string>> temp;
      int j;
      while(found!=string::npos){
         if(isPalindrome(s.substr(found+i, pos-i-found+1))){
         if((found+i)==0){
           line.clear();
           line.push_back(s.substr(found+i, pos-i-found+1));
           result.push_back(line);
         }
         else{
            temp.clear();
            temp = findPartition(s, found+i-1);
            for(j=0; j<temp.size(); j++){
               temp[j].push_back(s.substr(found+i, pos-i-found+1));
               result.push_back(temp[j]);
            }
         }
         }
         i = found+i+1;
         if(i<s.length()){
         newString = s.substr(i, pos-i);
         found = newString.find(s[pos]);
         }
         else{
          found = string::npos;
         }
      }
     
      return result;
    }
    vector<vector<string>> partition(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = s.length();
        vector<vector<string>> result;
        if(size==0) return result;
        return findPartition(s, size-1);
    }
};

No comments:

Post a Comment