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

【LeetCode】Longest Valid Parentheses

时间:2014-12-18 11:48:19      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   sp   for   strong   

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 ret = 0;
        stack<int> stk;   //store the indexes of unmatched parentheses
        for(int i = 0; i < s.size(); i ++)
        {
            if(s[i] == ()
            //unmatch
                stk.push(i);
            else
            {//s[i] == ‘)‘
                if(!stk.empty() && s[stk.top()] == ()
                //match
                    stk.pop();
                else
                //unmatch
                    stk.push(i);
            }
        }
        if(stk.empty())
        //all match
            ret = s.size();
        else
        {//check every unmatched pair of parentheses
            int start;
            int end = s.size()-1;
            while(!stk.empty())
            {
                start = stk.top();
                stk.pop();
                ret = max(ret, end-start);
                end = start-1;
            }
            //from begin to the first unmatched parenthese
            ret = max(ret, end+1);
        }
        return ret;
    }
};

bubuko.com,布布扣

【LeetCode】Longest Valid Parentheses

标签:style   blog   http   ar   io   color   sp   for   strong   

原文地址:http://www.cnblogs.com/ganganloveu/p/4171193.html

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