32. Longest Valid Parentheses
来源:互联网 发布:百强家具怎么样知乎 编辑:程序博客网 时间:2024/05/06 03:31
Longest Valid Parentheses(**多看)
计算最长的有效括号
题意
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.
Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.
思路:
使用动态规划DP:
建立一个空数组长度为给定的字符串n 依次对应给定的字符串字符 然后通过计算得到每位字符所对应的值
(( ) ( )( ( )
0 0 2 0 4 0 0 6
下面的代码很好,程序运行复杂度也很小2ms,此算法非常值得参考
代码
public class Solution{ public int longestValidParentheses(String s) { int n = s.length(), max = 0; int[] matched = new int[n]; //建立一个数组 for (int right = 1; right < n; right++) { if (s.charAt(right) == ')') { //注意从1开始,先检测右边‘)’的值 int left = right - 1 - matched[right - 1]; //检测到以后,计算与之相对应的左边的‘(’的位置 if (left >= 0 && s.charAt(left) == '(') { matched[right] = matched[right - 1] + 2; //得到每次()的长度 if (left - 1 > 0) matched[right] += matched[left - 1]; //需累计算出有效长度 } } max = max <= matched[right] ? matched[right] : max; //得出最大的值 } return max; }}
0 0
- 32.Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 李白打酒
- Dubbo入门
- 垂直菜单特效--移动端
- 2016.3.1
- 输入框回车莫名触发button点击事件
- 32. Longest Valid Parentheses
- DataGridView中的数据导出至Excel
- Java设计模式--代理模式
- 如何理解HTTP协议的 “无连接,无状态” 特点?
- Unity 基础
- 开博客的第一天,写点东西纪念下~
- Mysql通用查询方法(采用泛型确定输入类型,BeanUtils进行对象封装)
- Mysql 存储过程生成订单号,解决分布式问题
- Codeforces 635A Orchestra 【水题】