leetcode——132—— 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.


思路

此题可以用动态规划求解。isPal[j][i]表示字符串s的子串s[j…i]是否为回文串,cut[i]表示子串s[0…i]所需要的最小分割数

如果遍历到i,此时cut[i-1]已经求出,此时cut[i]最多分割cut[i-1]+1次

1.判断s[i-1,1]是否是回文子串,如果是回文子串,则cut[i] = min(cut[i],cut[i-2]+1);

2.判断s[i-2,1]是否是回文子串,如果是回文子串,则cut[i] = min(cut[i],cut[i-3]+1);

class Solution {
public:
	int minCut(string s) {
		int size = s.size();
		if (size == 0){
			return 0;
		}//if
		// isPal[i][j]表示字符串s的子串s[i,j]是否为回文串
		bool isPal[size][size];
		memset(isPal, 0, sizeof(isPal));
		// cut[j]表示子串s[0,j]所需要的最小分割数
		int cut[size];
		// cut[0,i]
		for (int i = 0; i < size; ++i){
			// [0,i]最多分割i次
			cut[i] = i;
			// 判断s[j,i]是否是回文串
			for (int j = 0; j <= i; ++j){
				// s[j,i]是回文串
				if(s[j] == s[i] && (i - j <= 1 || isPal[j+1][i-1]))
				{
					isPal[j][i] = true;
					if(j == 0)	{
                            cut[i] = 0;
                        }//if
                        else{
                            cut[i] = min(cut[i],cut[j-1]+1);
                        }//else

				}//if
			}//for
		}//for
		return cut[size - 1];
	}
};

 

你可能感兴趣的:(leetcode——132—— Palindrome Partitioning II)