Longest valid Parentheses(括号匹配长度问题)

原文地址:https://leetcode.com/problems/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.使用栈 O(n)和O(n)

栈用来记录 左括号的位置,遇到'('  就将其位置下标入栈,遇到')',如果栈不空,就出栈,并且计算答案(两种情况,分出栈后栈为空和不为空);如果栈空,则设定一个变量记录最右边的')'。

class Solution {
public:
    int longestValidParentheses(string s) {
        int max_len = 0,last = -1;//the position of the last ')'
        stack<int> lefts;// keep track of the positions of non-matching '('s
        
        for(int i = 0;i<s.size();++i){
            if(s[i]=='(')
            {
                lefts.push(i);
            }
            else{
                if(lefts.empty()){
                    last=i;//no matching left
                }
                else{
                    //find a matching pair
                    lefts.pop();
                    if(lefts.empty()){
                        max_len = max(max_len,i-last);
                    }
                    else{
                        max_len=max(max_len,i-lefts.top());
                    }
                }
            }
        }
        return max_len;
    }
};


2.两边遍历 O(n)和O(1)

直接用一个变量来记录最右边右括号的位置start,用一个变量depth来记录左括号的个数,遇到'(',就加1,遇到')', 就减1,如果这个变量为0了,那就计算长度,小于0了,就重新给赋值start。  但是一遍循环会出现得不到结果的情况,比如'(()',一遍遍历后,depth>0,没有结果,所以我们需要两次遍历,第二遍反过来遍历一遍,遇到')',depth++,依次类推。

代码:

class Solution {
public:
    int longestValidParentheses(string s) {
      int res = 0,depth = 0,start = -1;
      for(int i = 0;i<s.length();++i){
          if(s[i]=='(')    depth++;
          else{
              depth--;
              if(depth<0){
                  depth=0;
                  start = i;
              }
              else if(depth==0){
                  res = max(res,i-start);
              }
          }
      }
      depth = 0,start = s.length();
      for(int i = s.length()-1;i>=0;--i){
          if(s[i]==')')    depth++;
          else{
              depth--;
              if(depth<0){
                  depth=0;
                  start = i;
              }
              else if(depth==0){
                  res = max(res,start-i);
              }
          }
      }
      return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值