码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 032 Longest Valid Parentheses

时间:2015-02-07 18:51:04      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

题目描述: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 032 Longest Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4279074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!