zoukankan      html  css  js  c++  java
  • Longest Valid Parentheses

    32. 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.

    Subscribe to see which companies asked this question

    Show Tags
    Hide Similar Problems
     (E) Valid Parentheses
     
    class Solution {
    public:
        int longestValidParentheses(string s) {
            int sSize  = s.size();
            int maxLen = 0;
            int start  = -1,end = 0;
            
            vector<int> matches(sSize,-1);//每个字符的匹配情况,字符为'('是值为-1,字符为')'时,值为其匹配的左括号的位置
            stack<int> stk;//左括号的位置
            
            for(int i=0;i<sSize;i++){
                if(s[i]=='('){
                    stk.push(i);
                    continue;
                }
                if(!stk.empty()){
                    start      = stk.top();
                    end        = i+1;                    
                    matches[i] = start;//与i这个位置发生匹配的字符的位置是node.index
                    while(start>0 && matches[start-1]!=-1){
                        start = matches[start-1];
                    }
                    maxLen = max(maxLen,end-start);        
                    stk.pop();
                }
            }
            return maxLen;
        }
    };
    /**
    (()(()))
     */
  • 相关阅读:
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    MySQL-数据库三范式
    去除IDEA中xml黄色背景
    git查看commit提交记录详情
    spring-定时任务<task:scheduled-tasks>
  • 原文地址:https://www.cnblogs.com/zengzy/p/5027241.html
Copyright © 2011-2022 走看看