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.

给定一个字符串s,用最少的次数将它拆分成多个回文子串。我们用动态规划来解决。首先我们用一个二维的布尔数组isPalin[][]记录当前子串是否是回文串,例如isPalin[i][j] = true,就代表了字符串中从字符i到字符j是回文子串。(当s.charAt(i) == s.charAt(j)并且i + 1 >= j - 1的时候,也就是对应了’aa‘和’a?a‘这两种情况,此时肯定为回文串)。用数组dp[]来记录每个阶段的最小值,如果检测到从第一个字符到当前字符为回文子串,那么dp[j] = 0, 因为不需要拆分所以为0; 如果从字符i开始到当前字符为回文子串并且i > 0,此时dp[j] = dp[i - 1] + 1。实现代码如下:

public class Solution {
public int minCut(String s) {
if(s == null) return 0;
boolean[][] isPalin = new boolean[s.length()][s.length()];
int[] dp = new int[s.length()];
for(int i = 0; i < dp.length; i++) {
int min = i;
for(int j = 0; j <= i; j++) {
if(s.charAt(j) == s.charAt(i) && (j + 1 >= i - 1 || isPalin[j + 1][i - 1])) {
isPalin[j][i] = true;
min = (j == 0) ? 0 : Math.min(min, dp[j - 1] + 1);
}
}
dp[i] = min;
}
return dp[s.length() - 1];
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值