Saturday, March 9, 2013

Palindrome Partitioning II (to optimize)

/*
Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
*/
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;
    }
   
    int findMinCut(string s, int pos){
       if(pos==0) return 0;
      
       char curr = s[pos];
       int found;
      
       int i=0;
       string newString = s.substr(i,pos-i);
       int result = findMinCut(s, pos-1)+1;
       while(newString.find(curr)!=string::npos){
            found = newString.find(curr);
            if(isPalindrome(newString.substr(found+1))){
              if((found+i)==0) result = 0;
              else result = min(result, findMinCut(s, i+found-1)+1);
            }
            i = found+1+i;
            newString = s.substr(i,pos-i);
       }
       return result;
    }
   
    int minCut(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = s.length();
        if(size<=0) return 0;
        return findMinCut(s, size-1);
    }
   
    };

No comments:

Post a Comment