Longest Valid Parentheses

来源:互联网 发布:淘宝运费模板如何删除 编辑:程序博客网 时间:2024/06/06 16:27

题目:
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、新建一个数组a[],用于记录是不是有效的括号;
2、新建一个堆栈,用于判断括号对数;
3、如果是有效的括号则a[i]为true,循环判断最长的有效值;
代码:

class Solution {public:    int longestValidParentheses(string s) {        int len=s.size();        bool *a=new bool[len];        memset(a,false,sizeof(bool)*len);        stack<int> stk;        for(int i=0;i<len;i++)        {            if(s[i]=='(') stk.push(i);            else if(s[i]==')' && !stk.empty()){                a[i]=true;                a[stk.top()]=true;                stk.pop();            }        }        int maxlen=0;        int calLen=0;        for(int i=0;i<len;i++)        {            if(a[i]) ++calLen;            else     calLen=0;            maxlen=max(maxlen,calLen);        }        return maxlen;        //return calLen;    }};
0 0
原创粉丝点击