LeetCode——Palindrome Partitioning II

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.

思路:这道题的思路可以借鉴 Palindrome Partitioning的思路,加以修改。
利用两处dp算法:
1、用来判断从i到j的子串是不是回文串
2、定义状态dp[i],表示字符串s的字串0到i,可以进行的最少分割。则最后dp[len-1]即为所要求的答案。
代码:
class Solution {
public:
	vector<vector<int> > vt;
	bool dpjudge(string &s, int i, int j) {
		if (i > j)
			return false;
		if (vt[i][j] != -1)
			return vt[i][j];
		if (i == j)
			return vt[i][j] = 1;
		if (s[i] != s[j])
			return vt[i][j] = 0;
		else {
			if (i + 1 == j)
				return vt[i][j] = 1;
			else
				return vt[i][j] = dpjudge(s, i + 1, j - 1);
		}
	}
	int minCut(string s) {
		int len = s.length();
		if (len < 2)
			return 0;
		vector<int> dp, tmp;
		dp.clear(), tmp.clear(), vt.clear();
		//初始化dp和vt
		for (int i = 0; i < len; i++) {
			dp.push_back(0);
			tmp.push_back(-1);
		}
		for (int i = 0; i < len; i++) {
			vt.push_back(tmp);
		}
		for (int i = 1; i < len; i++) {
			if (dpjudge(s, 0, i)) {
				dp[i] = 0;
				continue;
			}
			int ans = i;
			for (int j = 0; j < i; j++) {
				if (dpjudge(s, j + 1, i))
					ans = min(ans, dp[j] + 1);
				else
					ans = min(ans, dp[j] + i - j);
			}
			dp[i] = ans;
		}
		return dp[len - 1];
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值