最长的合法括号
来源:互联网 发布:f1弹出windows media 编辑:程序博客网 时间:2024/05/01 05:25
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.
维护一个栈,栈底值为上次匹配失败的位置
首先初始放一个-1入栈代表上次匹配失败的地方为-1
依次扫描字符
若为'(',将位置放入栈中
若为')',若栈中元素大于1个,则代表有'('可匹配,更新最优值,否则更新栈底
显然,对于任意一个部分最长子串,其最后一个字符更新时取的是上一次匹配失败的位置,故所有部分最长子串取得最优结果
class Solution{public: int longestValidParentheses(string s) { stack<int>S; S.push(-1); int ans=0; for(string::size_type i=0;i<s.size();i++) { //printf("%d\n",S.size()); char ch=s[i]; if(ch == '(') { S.push(i); } else { if(S.size()>1) { S.pop(); int tmp=S.top(); ans=max(ans,(int)i-tmp); } else { S.pop(); S.push(i); } } } return ans; }};
0 0
- 最长的合法括号
- 求解最长的合法括号
- 32.最长的合法括号匹配
- 括号序列的最长合法子段
- 最长合法括号序列
- 51nod 1478 括号序列的最长合法子段
- Longest Valid Parentheses 最长的合法括号序列
- 1478 括号序列的最长合法子段
- 51Nod-1478-括号序列的最长合法子段
- 51nod-1478 括号序列的最长合法子段
- 1478 括号序列的最长合法子段
- 51nod 1478 括号序列的最长合法子段
- 合法的括号
- 合法的括号匹配
- 合法的括号序列
- 栈+括号配对 51Nod1478 括号序列的最长合法子段
- 51nod 1478 括号序列的最长合法子段 (括号匹配)
- [LeetCode] 最长合法括号 longest valid parentheses
- Integer的MIN_VALUE
- 《Java编程思想》学习笔记3——内部类
- 4种常用的linux命令
- 数据库连接池c3p0常用参数设置及解析
- iterator demo
- 最长的合法括号
- I love sneakers!(最少分配一个问题)
- 用mii-tool命令查看和修改网卡工作模式
- leetcode -- Combination Sum
- msSQL 引起磁盘空间不足的解决方法
- java基础巩固之常用类
- LINQ小结
- qt5学习问题笔记(从零开始)
- 多线程和多进程的区别(小结)