【32】Longest Valid Parentheses

来源:互联网 发布:中俄贸易数据统计 编辑:程序博客网 时间:2024/06/10 09:45

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.


dp+栈。用一个dp数组来存储结果,dp[i]表示以第i个位置的括号结尾所能得到的最长合法子串长度,则所有的左括号位置对应的dp值都是0。以)(()()))为例,其dp的值依次为0,0,0,2,0,4,6,0。那么我们得到这个dp数组的值后只要从前到后扫一遍取出最大的值就可以了。

而这个dp数组,我们需要借助一个栈来计算:

从前到后遍历原始的字符串,如果在第i个位置碰到一个'(',令dp[i]=0,并把i压入栈中;

如果在第i个位置碰到一个')',这时我们需要先看下栈是否为空。如果栈为空则表示当前没有'('可与这个')'配对,则dp[i]=0;如果栈不为空,弹出栈顶元素pos,它记录的是与这个')'配对的'('的位置,易知pos和i之间的序列一定都是合法的,那么dp[i]=dp[pos-1]+(i-pos+1);


int longestValidParentheses(string s) {    int n = s.length();    int *dp = new int [n+1];    memset(dp,0,sizeof(int)*(n+1));    stack<int> st;    for(int i=1;i<=n;i++){        if(s[i-1]=='('){            dp[i]=0;            st.push(i);        }        else{            if(st.empty()){                dp[i]=0;            }            else{                int pos=st.top();                st.pop();                dp[i]=dp[pos-1]+(i-pos+1);            }        }    }    int max_len=0;    for(int i=1;i<=n;i++){        if(dp[i]>max_len)max_len=dp[i];    }    return max_len;}


0 0
原创粉丝点击