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;

        

    }

};

 

你可能感兴趣的:(LeetCode)