Brackets Sequence 括号DP
2015-07-21 20:26
323 查看
Brackets Sequence
题目抽象:给你一个括号字符串,要求你加入最好的括号使得括号匹配。输入匹配后的括号字符串。
分析:由已知的子区间推出大的区间。 cnt[i][j]表示原字符串[i,j]中至少需要加入的括号数。 ans[i][j]存储原字符串[i,j]匹配后的字符串。
特别注意输入的是空字符串。空字符串是匹配的字符串。
题目抽象:给你一个括号字符串,要求你加入最好的括号使得括号匹配。输入匹配后的括号字符串。
分析:由已知的子区间推出大的区间。 cnt[i][j]表示原字符串[i,j]中至少需要加入的括号数。 ans[i][j]存储原字符串[i,j]匹配后的字符串。
特别注意输入的是空字符串。空字符串是匹配的字符串。
import java.util.*; import java.io.*; import java.math.*; public class Main { static Scanner cin = new Scanner(new BufferedInputStream(System.in)); public final static int MS= 105; static int[][] cnt = new int[MS][MS]; static String[][] ans = new String[MS][MS]; public static void main(String[] args) { String str = cin.nextLine(); str.replaceAll(" ",""); if(str.length() == 0) { System.out.println(); System.exit(0); } char[] ch = str.toCharArray(); int len = ch.length; for(int i = 0 ;i<len;i++) for(int j = i;j< len;j++) cnt[i][j] = Integer.MAX_VALUE; for(int i = 0;i<len;i++) Arrays.fill(ans[i], ""); for(int i = len -1;i>=0;i--) { for(int j = i;j<len;j++) { if(i == j) { cnt[i][j] = 1; if(ch[i] == '(' || ch[i] == ')') ans[i][i] = "()"; else ans[i][i] = "[]"; } else { if(ch[i] == '(' && ch[j] == ')') { if(cnt[i+1][j-1] < cnt[i][j]) { cnt[i][j] = cnt[i+1][j-1]; ans[i][j] = "(" + ans[i+1][j-1] + ")"; } } else if(ch[i] == '[' && ch[j] == ']') { if(cnt[i+1][j-1] < cnt[i][j]) { cnt[i][j] = cnt[i+1][j-1]; ans[i][j] = "[" + ans[i+1][j-1] + "]"; } } // 求 cnt[i][j]的最小值。 for(int k = i;k<j;k++) { if(cnt[i][k] + cnt[k+1][j] < cnt[i][j]) { cnt[i][j] = cnt[i][k] + cnt[k+1][j]; ans[i][j] = ans[i][k] + ans[k+1][j]; } } } } } System.out.println(ans[0][len-1]); } }
相关文章推荐
- 修改UIImage大小
- HDU 2818 - Building Block
- UIButton的一些设置
- 2015 Multi-University Training Contest 1 Hdu 5297 Y sequence
- hdu5288(2015多校1)OO’s Sequence
- iOS开发-UITableViewCell(UICollectionViewItem)需要两个手指点击或者长按才可以选中,解决办法
- 多校第一场 1001 hdu 5288 OO’s Sequence(枚举)
- HDU 5288 OO’s Sequence 区间个数
- 2015 Multi-University Training Contest 1 OO’s Sequence
- 多校7.21A——维护技巧——OO’s Sequence
- UITabBarItem初始化详解及UIImage渲染模式
- UILabel 垂直居中问题
- iOS UIView 快速修改 frame,避免累赘的书写方式
- hdu 5288OO’s Sequence
- Failed to instantiate the default view controller for UIMainStoryboardFile 'Main1' - perhaps the des
- uva 10746 Crime Wave - The Sequel (最小费最大流)
- MiniGUI鼠标热插拔支持
- 【瞎搞】HDU 5288 OO’s Sequence
- Rescue-优先队列
- 进入UI_UiView;frame和bound以及视图之间层级关系