32. Longest Valid Parentheses
来源:互联网 发布:淘宝火拼 编辑:程序博客网 时间:2024/05/21 01:28
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.
Subscribe to see which companies asked this question.
找到最长的有效的括号对子字符串。对一个右括号')',有效的情况是,它的左边是一个左括号'(',或者是一个有效的括号对子字符串,然后该子字符串的左边是左括号'('。用数组保存包含每个位置且以该位置为结尾的有效的括号对子字符串的长度。对每个右括号,左括号或许在它的左边,或许在它左边的有效括号对子字符串的左边,如果找到计算它与对应的左括号之间的距离(包括两个括号),如果这对括号的左边还是有效的括号对子字符串,就连接上,将子字符串长度保存在数组的对应位置上。求子字符串长度的最大值即可。
代码:
class Solution{public:int longestValidParentheses(string s) {int i = 0, res = 0, cnt = 0, n = s.size();vector<int>len(n, 0);while(s[i++] == ')');for(i; i < n; ++i){if(s[i] == ')'){if(i == 1){len[i] = 2;}else{if(i - 1 - len[i-1] >= 0 && s[i - 1 - len[i-1]] == '('){len[i] = 2 + len[i-1];}else{len[i] = 0;}}if(len[i - len[i]] > 0) len[i] += len[i - len[i]];res = max(res, len[i]);}}return res;}};
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
- 手把手教你制作linux U盘启动盘及安装Ubuntu与win7双系统
- msf生成安卓渗透
- java swing flowlayou 方式
- 数据库的导出指令
- 动态给ViewPager添加Indicator导航
- 32. Longest Valid Parentheses
- java swing borderLayout
- veil-evasion 在xp下的三分之二免杀
- C++ 中各种类型的表示范围
- bypass UAC 提权
- hibernate 标准 ORM框架
- javascript-MDN笔记-对象
- 用C语言实现打印菱形
- 筋斗云接口编程 / 创建Web接口项目