题目: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.
思路:
本题就是如果是“(”,进入堆栈,如果不是:
看当前栈是否落空,落空就是从头计起,
如果不是记录当前栈顶元素,并且出栈,如果栈为空,表示可以记录一下当前值,加上刚刚的accu值,这是因为可能出现()()的情况,所以加上accu;
如果栈不为空,比如是(()所以就是i-j+1,当然这些都是要与之前的res取最大值。
代码:
class Solution { public: int longestValidParentheses(string s) { int res=0,first=0; stack<int>stk; for(int i=0;i<s.size();i++){ if(s[i]=='('){ stk.push(i);//stack 仅仅存放当前“(”的索引值 }else{ if(stk.empty()){ first=0; }else{ int j=stk.top(); stk.pop(); if(stk.empty()){ first+=i-j+1; res=max(res,first); }else{ res=max(res,i-stk.top()); } } } } return res; } };