0
点赞
收藏
分享

微信扫一扫

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:栈
用一个变量_max表示当前最长匹配的括号数
不存右括号,只存左括号的index。扫描一遍字符串,
如果当前的字符是'(',则压栈
如果当前的字符是')',则
1.若栈空,则当前的')'没有一个'('与它匹配,它可以作用它左右两个匹配的括号串的分割点,用一个变量 last 记录下它的坐标。
last的初始值是-1,当遇到新的分割点时,我们更新 last,并可以得到两个 last之间的匹配括号的长度
2.若栈非空,则当前的')'与栈顶的'('匹配
将栈顶元素出栈
如果此时栈为空,则找到了一组匹配括号串,更新 _max = max(_max, last - i)
如果此时栈不空,则栈顶的'('还没找到它的')',因为栈顶元素有可能找不到它的')',因此,此时要更新 _max = max(_max, i - stack.top())

复杂度:时间O(n),空间O(n)

class Solution {
 public:
         int longestValidParentheses(string s) {
         int _max = 0, last = -1;
         stack<int> stack;
         for(int i = 0;  i < s.size(); ++i){
         if(s[i] == '(') stack.push(i);
         else{
             if(stack.empty()) last = i;
             else{
                 stack.pop();
                 if(stack.empty()){
                     _max = max(_max, i - last);
                 }else{
                     _max = max(_max, i - stack.top());
                 }
             }
         }
     }
     return _max;    
     }
 };

举报

相关推荐

0 条评论