最长的合法括号

来源:互联网 发布:f1弹出windows media 编辑:程序博客网 时间:2024/05/01 05:25

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.

维护一个栈,栈底值为上次匹配失败的位置

首先初始放一个-1入栈代表上次匹配失败的地方为-1

依次扫描字符

若为'(',将位置放入栈中

若为')',若栈中元素大于1个,则代表有'('可匹配,更新最优值,否则更新栈底

显然,对于任意一个部分最长子串,其最后一个字符更新时取的是上一次匹配失败的位置,故所有部分最长子串取得最优结果

class Solution{public:    int longestValidParentheses(string s)    {        stack<int>S;        S.push(-1);        int ans=0;        for(string::size_type i=0;i<s.size();i++)        {            //printf("%d\n",S.size());            char ch=s[i];            if(ch == '(')            {                S.push(i);            }            else            {                if(S.size()>1)                {                    S.pop();                    int tmp=S.top();                    ans=max(ans,(int)i-tmp);                }                else                {                    S.pop();                    S.push(i);                }            }        }        return ans;    }};



0 0