您的位置:首页 > 其它

LeetCode 132. Palindrome Partitioning II(回文切分)

2016-05-27 00:22 507 查看
原题网址:https://leetcode.com/problems/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.
方法:动态规划。

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