32. Longest Valid Parentheses
来源:互联网 发布:卸载加密软件 编辑:程序博客网 时间:2024/06/07 05:15
Description:
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.
简要题解:
从左到右开始统计,无论何时左括号的数量一定都大于或等于右括号的数量。
类似地,从右到左开始统计,无论何时右括号的数量一定都大于或等于左括号的数量。
可以先从左边开始顺序地向右移动,计算出所有有效括号子串的长度,不断更新“当前最大长度”。
由于缺乏对称性,所以想要遍历所有情况必须再从右往左计算一遍。原理类似。最后得出的“当前最大长度”就是所要求的最大长度。
代码:
class Solution {public: int longestValidParentheses(string s) { int maxLength = 0, l = 0, r = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') l++; else r++; if (l == r) maxLength = (l + r > maxLength) ? l + r : maxLength; if (l < r) l = r = 0; } l = r = 0; for (int i = s.size() - 1; i >= 0; i--) { if (s[i] == '(') l++; else r++; if (l == r) maxLength = (l + r > maxLength) ? l + r : maxLength; if (l > r) l = r = 0; } return maxLength; }};
阅读全文
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
- jquery使用append动态增加元素,该元素绑定事件失效的解决办法
- 个人笔记1
- mybatis 参数传递总结
- 3Sum--LeetCode
- HDU
- 32. Longest Valid Parentheses
- JavaScript连续赋值的思考
- redis事物的开启和终止
- nginx第三方模块---nginx-sticky-module的使用(基于cookie的会话保持)
- SpringMvc三大组件详解
- HTTP学习(1)
- GitHub 优秀的 Android 开源项目
- 我与大boss的战斗开始了
- Kubernetes中controller-manager源码分析--启动流程