LeetCode -- Longest Valid Parentheses
2015-09-25 11:47
323 查看
题目描述:
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.遍历s[i] ,i∈[0,n)并使用stack存当前索引i
2.如果s[i] 为 ')' 且stack不为空 且s[stack.Peek()] 为'('
:stack弹出
如果stack为空 , max = i + 1
否则,max = Max(max,i-stack.Peek())
否则(即s[i]为'('),直接将s[i]入栈
实现代码:
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.遍历s[i] ,i∈[0,n)并使用stack存当前索引i
2.如果s[i] 为 ')' 且stack不为空 且s[stack.Peek()] 为'('
:stack弹出
如果stack为空 , max = i + 1
否则,max = Max(max,i-stack.Peek())
否则(即s[i]为'('),直接将s[i]入栈
实现代码:
public class Solution { public int LongestValidParentheses(string s) { int max = 0; var stack = new Stack<int>(); for (int i = 0; i < s.Length; i++) { if (s[i] == ')' && stack.Count > 0 && s[stack.Peek()] == '(') { stack.Pop(); if (stack.Count == 0){ max = i + 1; } else{ max = Math.Max(max, i - stack.Peek()); } } else { stack.Push(i); } } return max; } }
相关文章推荐
- 1.v4l2 framework框架
- C++中的空类,默认产生哪些类成员函数?
- 如何通过投资理财来解决人生350万亏空
- OPENWRT make menuconfig错误之一
- 2015北京网络赛 J Scores bitset+分块
- (转载)基于LBS地图的开发,满足地图上有头像的需求
- Linux学习日记--基础命令(7)--bash中的变量,配置文件
- 关于Xcode 的一些调试技巧
- JS只能输入数字并限制长度的实用代码
- 开源项目地址集合
- lnmp下如何关闭Mysql日志保护磁盘空间
- qt用http协议访问webservice,用crypto的sha256签名
- itemSelectedListener与itemClickListener的区别
- C++ 11 - STL - 函数对象(Function Object) (中)
- 根据经纬度计算距离
- codeforces 573C Bear and Drawing
- Android 各大网络请求库的比较及实战
- Linux学习日记--基础命令(6)--grep及正则表达式
- 10个C#程序员经常用到的实用代码片段
- LeetCode -- Insert Interval