2014年8月28日星期四
[Leetcode]Longest Valid Parenthese
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.
这道题只需要从左到右扫描一遍就可以,分为下面的情况
如果碰到的是(,则压栈,压入当前扫描的位置
如果碰到的是),则
1. 如果栈为空,则说明到该位置并不符合条件,即左括号个数<右括号个数,且不存在某个中间位置i,使得从i到b是符合条件的,也就是能够从中间开始,因为如果存在这样的i,则a到i是符合条件的,i到b是符合条件的,也就是说a到b是符合条件的,所以这段结束了就可以记录一下b的位置,记为last
2. 如果栈不为空,则弹栈,还分下面两种情况
2.1 若此时栈为空,则max_len更新为max(i - last, max_len)
2.2 若此时栈不为空,则更新max_len为max(max_len, i - s.top()),s.top()到i的距离,也就是说在s.top()和i之间的是符合条件的没有问题
订阅:
博文评论 (Atom)
没有评论:
发表评论