zoukankan      html  css  js  c++  java
  • LeetCode_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.
    

      用一个stack来维护上一个未匹配的位置,当出现匹配情况时更新最大值

    class Solution {
    public:
        int longestValidParentheses(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
         
            int n = s.length();
            if(n < 2) return 0;
            
            int maxR = 0 , top,result ;
            stack<int> myS;
            
            for(int i = 0; i < n; i++)
            {
              if(s[i] == '(' || myS.empty())
                    myS.push(i);
                    
              else 
              {
                 top = myS.top();
                 if(s[top] == '(')                
                 {
                    myS.pop();  
                    result = myS.empty()? i+1: i - myS.top();
                    maxR = maxR > result ? maxR : result ;
                }else   
                    myS.push(i);  
                 
              }
            }
            
            return maxR;
        }
    };
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    D
    A
    D
    G
    H
    E
    F
    B
    D
    oracle中新建用户和赋予权限
  • 原文地址:https://www.cnblogs.com/graph/p/3095962.html
Copyright © 2011-2022 走看看