Longest Valid Parentheses 最长的连续匹配数

来源:互联网 发布:mp3购买推荐淘宝网 编辑:程序博客网 时间:2024/06/05 11:18

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:/*用一个bool数组来标记已经匹配过的字符,找到最长的连续标记的长度就是所求的结果。只要遍历两遍数组,时间复杂度为O(n)。*/    int longestValidParentheses(string s) {                int len=s.length();        bool *a=new bool[len];        memset(a,false,len);        stack<int> ss;                for(int i=0;i<len;i++)        {            if(s[i]=='(')                ss.push(i);//右括号,坐标入栈            else if(s[i]==')' && !ss.empty())//左括号,栈不为空,匹配            {                a[i]=true;                a[ss.top()]=true;                ss.pop();            }        }                int maxLen=0,sum=0;        for(int i=0;i<len;i++)        {            if(a[i])                sum++;            else                sum=0;            if(sum>maxLen)                maxLen=sum;        }        return maxLen;    }};

0 0
原创粉丝点击