• LeetCode 032 Longest Valid Parentheses


    题目描述: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.

    代码如下:

    class Solution {
    public:
        int longestValidParentheses(string s) {
            
            int max_len = 0, last = -1; //last是上一次的')'的位置
            stack<int> lefts;       
            
            for(int i = 0; i < s.size(); i++){
                
                //s[i]为'(',则将i入栈
                if(s[i] == '(') 
                    lefts.push(i);
                
                //s[i]为')'
                else{
                    if(lefts.empty()) 
                        last = i;
                    else{
                        lefts.pop();
                        
                        //若栈为空,则
                        if(lefts.empty()) 
                            max_len = max(max_len, i - last);
                        else 
                            max_len = max(max_len, i - lefts.top());
                    }
                }
            }
            
            return max_len;
            
        }
    };
  • 相关阅读:
    示波器测量电源的纹波
    hdoj 2717 Catch That Cow
    hdoj 1548 A strange lift
    hdoj 4586 Play the Dice
    zoj 2095 Divisor Summation
    hdoj 4704 Sum
    router-link传参
    字体自适应
    横向滚动div
    vue路由
  • 原文地址:https://www.cnblogs.com/510602159-Yano/p/4279074.html
Copyright © 2020-2023  润新知