您的位置:首页 > 其它

LeetCode 132 Palindrome Partitioning II

2017-06-26 14:28 441 查看
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.

思路:1.推断字符串的字串S.subString(i,j) [i<=j]是否为为回文子串,用boolean型的二维数组isPalindrome来存储该结果。

在这个地方用了点小技巧,isPalindrome[i]j]会依赖于sPalindrome[i+1]j-1]
[i+2<=j].

2.使用动态规划的思想,若S.subString(i,j) 是回文字符串,则仅仅要看 ans[i] - 1 > ans[j - 1]是否成立,若成立,则更新他。

public class Solution {
public int minCut(String s) {
int[] ans = new int[s.length()];
boolean[][] isPalindrome = new boolean[s.length()][s.length()];
for (int i = 0; i < s.length(); i++)
isPalindrome[i][i] = true;

for (int i = 0; i < s.length() - 1; i++)
isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1));

for (int length = 2; length < s.length(); length++) {
for (int start = 0; start + length < s.length(); start++) {
isPalindrome[start][start + length]
= isPalindrome[start + 1][start + length - 1] && s.charAt(start) == s.charAt(start + length);
}
}

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