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 =
Return
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]是否成立,若成立,则更新他。
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s =
"aab",
Return
1since 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]; } }
相关文章推荐
- [LeetCode]132. Palindrome Partitioning II
- Leetcode 132. Palindrome Partitioning II
- 【LeetCode】132.Palindrome Partitioning II
- Leetcode 131&132. Palindrome Partitioning I & II
- leetcode132 Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II(回文切分)
- Leetcode 132. Palindrome Partitioning II (Hard) (cpp)
- [LeetCode 132] - 回文分割II(Palindrome Partitioning II)
- [Leetcode] 132. Palindrome Partitioning II
- Leetcode 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(Java)
- LeetCode 132 Palindrome Partitioning II
- Leetcode(132) Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II
- leetcode 132: Palindrome Partitioning II
- LeetCode: Palindrome Partitioning II [132]