CODE 1: Palindrome Partitioning II

本文介绍了一种使用动态规划算法解决回文分割问题的方法,通过构建回文矩阵并计算最小切割次数,实现了字符串的最优回文划分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

	/**
	 * 使用动态规划计算任意两点间是否为回文
	 * @param s 字符串
	 * @return  最小Cut次数
	 */
	private int partition(String s) {
		if (s == null || s.length() == 0)
			return 0;
		
		boolean[][] isPalindromes = new boolean[s.length()][s.length()]; // 表示任意两点之间的字符串是否为回文

		for (int i = 0; i < s.length(); i++) {
			isPalindromes[i][i] = true;
		}
		for (int i = s.length() - 2; i >= 0; i--) {
			isPalindromes[i][i + 1] = s.charAt(i) == s.charAt(i + 1);
			for (int j = i + 2; j < s.length(); j++)
				isPalindromes[i][j] = (s.charAt(i) == s.charAt(j)) && isPalindromes[i + 1][j - 1];
		}

		return getMinCut(s, isPalindromes);
	}

	/**
	 * 使用动态规划计算最小Cut次数
	 * @param s 字符串
	 * @param isPalindromes 表示任意两点之间的字符串是否为回文
	 * @return
	 */
	private int getMinCut(String s, boolean[][] isPalindromes) {
		int[] cuts = new int[s.length()];
		for (int i = s.length() - 1; i >= 0; i--) {
			if (isPalindromes[i][s.length() - 1]) {
				cuts[i] = 0;
				continue;
			}
			int min = Integer.MAX_VALUE;
			for (int j = s.length() - 2; j >= i; j--) {
				if (isPalindromes[i][j]) {
					int tmp = 1 + cuts[j + 1];
					min = min > tmp ? tmp : min;
				}
			}
			cuts[i] = min;
		}
		return cuts[0];
	}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值