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 =
Return
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;
}
}
"aab",
Return
1since 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;
}
}
相关文章推荐
- 132. Palindrome Partitioning II (动态规划)
- [LeetCode]132. Palindrome Partitioning II
- 132. Palindrome Partitioning II
- Leetcode 132. Palindrome Partitioning II (Hard) (cpp)
- 132. Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II--In C++
- LeetCode132 Palindrome Partitioning II
- 132. Palindrome Partitioning II
- leetcode || 132、Palindrome Partitioning II
- LeetCode132 Palindrome Partitioning II&I
- [LeetCode]132 Palindrome Partitioning II
- LeetCode132:Palindrome Partitioning II
- Leetcode(132) Palindrome Partitioning II
- LeetCode #132: Palindrome Partitioning II
- [LeetCode]题解(python):132-Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II (动态规划)
- 132. Palindrome Partitioning II
- leetcode 132 —— Palindrome Partitioning II