13.3 Palindrome Partitioning II
来源:互联网 发布:网络诈骗有哪些形式 编辑:程序博客网 时间:2024/06/01 09:21
Link: https://oj.leetcode.com/problems/palindrome-partitioning-ii/
Approach: DP
Time: O(n^2), Space: O(n^2)
public class Solution { public int minCut(String s) { boolean[][] dict = buildDict(s); int[] cuts = new int[s.length()+1]; cuts[0] = 0; for(int i = 0; i < s.length(); i++){ cuts[i+1] = i+1;//we can cut at most i+1 times at position i+1 for(int j = 0; j <=i; j++){ if(dict[j][i]){//if j...i is a palindrome, then we only need to add a cut after i cuts[i+1] = Math.min(cuts[i+1], cuts[j]+1); } } } return cuts[s.length()]-1;//the final cut after the last char is unnecessary? } public boolean[][] buildDict(String s){ boolean[][] dict = new boolean [s.length()][s.length()]; for(int i = s.length()-1; i>=0; i--){ for(int j = i; j < s.length(); j++){ if(s.charAt(i) == s.charAt(j) && (j-i<2 || dict[i+1][j-1])){ dict[i][j] = true; } } } return dict; }}
Note:
- In buildDict, since i decreases and j increases, so dict[i+1][j-1] has been computed before dict[i][j]. That's why we can check dict[i+1][j-1] and decide dict[i][j] if(s.charAt(i) == s.charAt(j) && (j-i<2 || dict[i+1][j-1])){
- cuts[i+1] = i+1 is the maximum cuts we can add at position i (See the Figure below). if j...i is a palindrome, then we only need to add a cut at cut position i+1//?
cuts[s.length()]-1
because in Math.min(cuts[i+1],cuts[j]+1),both cuts[i+1]=i+1, and cuts[j]+1, have added the last cut after the last char,this is unnecessary, so we decrease the final result by one.
0 0
- 13.3 Palindrome Partitioning II
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- Palindrome Partitioning II
- Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- Palindrome Partitioning II
- LetCode:Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- 自动代码复制工具
- VS2010通过Nuget无法初始化 PowerShell 主机
- ActionScript3游戏中的图像编程(连载十三)
- ACdream 1142 String opearation
- 《小时代2青木时代》 短评 与郭敬明的中立评价
- 13.3 Palindrome Partitioning II
- 遍历文件夹下所有文件
- HDU-4885-TIANKENG’s travel
- 10 Articles Every Programmer Must Read
- 网卡故障:弹出界面eth0: 错误:没有找到合适的设备:没有找到可用于链接System eth0 的
- 13.4 Maximal Rectangle
- 快速高斯滤波函数[修正完善版]
- python正则表达式
- vs2012离线语言安装包(英文) + 安装方法