LeetCode 131: Palindrome Partition

Difficulty: 3

Frequency: 4


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


Solution:

class Solution {
public:
    vector<vector<string> > partition(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (s.size()==1)
        {
            return *(new vector<vector<string> >(1,(*(new vector<string>(1,s)))));
        }
        vector<vector<string>> answer;
        vector<char> v_current(1, 1);
        DFS(s, 0, 0, v_current, answer);
        return answer;
    }
    bool CheckPalindrome(string s, int i_begin, int i_end)
    {
    	if (i_begin>i_end)
			return false;

        while(i_begin<i_end)
        {
            if (s[i_begin]!=s[i_end])
                return false;
                
            ++i_begin;
            --i_end;
        }
        return true;
    }
    void DFS(const string & s, int i_begin, int i_last, vector<char> & v_current, vector<vector<string> > & answer)
    {
        if (i_begin==s.size()-1)
        {
			if (CheckPalindrome(s, i_last, i_begin))
			{
                vector <string> palindromes;
                string palin;
				palin+=s[0];
                for (int i=1; i<v_current.size(); i++)
                {
                    if (v_current[i]==1)
                    {
                        palindromes.push_back(palin);
                        palin.clear();
                    }   
                    palin+=s[i];
                }
                palindromes.push_back(palin);
				answer.push_back(palindromes);
			}
            return;
        }
        v_current.push_back(0);
        DFS(s, i_begin+1, i_last, v_current, answer);
        v_current.pop_back();
        if (CheckPalindrome(s, i_last, i_begin))
        {
            v_current.push_back(1);
            DFS(s, i_begin+1, i_begin+1, v_current, answer);
            v_current.pop_back();
        }
    }
};

Note:

This is the first time I try to code in this problem. The code may be messy. I will consult for other's code someday.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值