首页 > 代码库 > leetcode题目:Palindrome Partitioning 和Palindrome Partitioning II

leetcode题目:Palindrome Partitioning 和Palindrome Partitioning II

题目一:

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"]
  ]
解题思路:

1)用一个二维数组来存取两者之间是否是回文。

2)从字符串尾部开始存入可能的回文串。

代码:

class Solution {
public:
	vector<vector<string>> partition(string s)
	{
		int len = s.size();
		vector<vector<bool>>f(len+1,vector<bool>(len));
		for (int i=1;i<len+1;i++)
		{
			for (int j = i-1;j>=0;j--)
			{
				if(ispalindrome(s,j,i-1)==1)
				{
					f[i][j]=true;
				}
			}
		}	
		dealstring(s,len,f);
		return m_str;
	}
private:
	vector<vector<string>>m_str;
	vector<string>m_temstr;
	void dealstring(string s,int count,const vector<vector<bool>>&f)
	{
		if (count == 0)
		{
			vector<string>oneanswer(m_temstr.rbegin(),m_temstr.rend());
			m_str.push_back(oneanswer);
		}
		for (int i=0;i<count;i++)
		{
			if (f[count][i])
			{
				m_temstr.push_back(s.substr(i,count-i));
				dealstring(s,i,f);
				m_temstr.pop_back();
			}
			
		}
		
	}
	int ispalindrome(string s,int i,int j)
	{
		while (i<j)
		{
			if (s[i]!=s[j])
			{
				return 0;
			}
			i++;
			j--;
		}
		return 1;
	}
};

题目二:

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.


解题思路:

1)用二维数组存入判断两者之间是否是回文。

2)同时用一个一维数组存取从这个点开始往右的最小切数。

代码:

class Solution {
public:
	int minCut(string s)
	{
	    int size = s.size();
	    int mincount[size+1];
	    vector<vector<bool> >m_bool(size,vector<bool>(size));
	    for(int i=0;i<=size;i++)
	    {
	        mincount[i] = size-1-i;
	    }
	    for(int j=size-1;j>=0;j--)
	    {
	        for(int k = j;k<size;k++)
	        if(s[j]==s[k]&&(k-j<2||m_bool[j+1][k-1]))
	        {
	            m_bool[j][k]=true;
	            mincount[j]=min(mincount[j],mincount[k+1]+1);
	        }
	    }
	    return mincount[0];
	}
};