Sunday, November 24, 2013

LeetCode Problem : Palindrome Partitioning


Problem

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

Code

void palTable(string s,int n,vector<vector<bool> >& p) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    for(int i = 0;i < n;++i)
        p[i][0] = true;
    for(int i = 0;i < n - 1;++i){
        if(s[i] == s[i+1]){
            p[i][1] = true;
        }
    }
    for(int len = 3;len <= n;++len){
        for(int i = 0;i <= n - len;++i){
            if(p[i+1][len-3] && s[i] == s[i + len - 1]){
             p[i][len - 1] = true;
            }
        }
    }
}
void partition_r(const string& str,int i,int n,const vector<vector<bool> >& p,
     vector<string>& result,int pos,vector<vector<string> >& vret){
    if(i == n){
        vector<string> tmp;
        for(int k = 0;k < pos;++k)
        tmp.push_back(result[k]);
        vret.push_back(tmp);
        return;
    }
    for(int j = 0;j < n - i;++j){
        if(p[i][j]){
            if(result.size() == pos)
            result.resize(2*pos + 1);
            result[pos] = str.substr(i,j + 1);
            partition_r(str,i + j + 1,n,p,result,pos + 1,vret);
        }
    }
}
vector<vector<string>> partition(string s) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = s.size();
    vector<vector<bool> > p(n,vector<bool>(n,false));
    palTable(s,n,p);
    vector<vector<string> > vret;
    vector<string> result;
    int pos = 0;
    partition_r(s,0,n,p,result,pos,vret);
    return vret;
}


No comments:

Post a Comment