首页 > 其他 > 详细

[LeetCode] #32 Longest Valid Parentheses

时间:2015-06-15 13:01:42      阅读:216      评论:0      收藏:0      [点我收藏+]

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.

本题是括号匹配问题,用栈存放‘(’,如果碰到‘)’就出栈。时间:17ms,代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        if (s.empty())
            return 0;
        stack< pair<char,int> > validStack;
        for (string::const_iterator iter = s.begin(); iter != s.end(); iter++){
            if (*iter == ()
                validStack.push(make_pair((,iter - s.begin()));
            else if (*iter == )){
                if (!validStack.empty() && validStack.top().first == (){
                    validStack.pop();
                }
                else
                    validStack.push(make_pair(*iter,iter - s.begin()));
            }
        }
        if (validStack.empty())
            return s.size();
        int temp = validStack.top().second;
        int max = s.size() - 1 - temp ;
        validStack.pop();
        while (!validStack.empty()){
            if (max < temp - validStack.top().second - 1)
                max = temp - validStack.top().second - 1;
            temp = validStack.top().second;
            validStack.pop();
        }
        if (max < temp)
            return temp;
        return max;
    }
};

 

[LeetCode] #32 Longest Valid Parentheses

原文:http://www.cnblogs.com/Scorpio989/p/4576684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!