您的位置:首页 > 其它

132. Palindrome Partitioning II

2018-03-27 21:21 543 查看
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.

题意:

给出一个字符串,求最少切几下,使得每个字符串都是回文串。

思路:

还是想不出来。。可以联想到之前的最长回文子序列与最长回文子串点击打开链接。可以使得判断回文串变得简单。首先用一个数组dp[i][j]表示i到j是否为回文串。如果s[i]==s[j]&&dp[i+1][j-1]==1,那么就dp[i][j]=1.再用一个cut数组表示从i到最后需要多少次,那么cut[i]=min(cut[i],cut[j+1]+1)。

代码:

class Solution {
public int minCut(String s) {
int l=s.length();
int [][]dp=new int[l][l];
int []cut=new int[l+1];
for(int i=l-1;i>=0;i--)
{
cut[i]=Integer.MAX_VALUE;
for(int j=i;j<l;j++)
{
if(s.charAt(i)==s.charAt(j)&&(j<=i+1||dp[i+1][j-1]==1))
{
dp[i][j]=1;
cut[i]=Math.min(cut[i],cut[j+1]+1);
}
}
}
return cut[0]-1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: