【ATT】Longest Valid Parentheses
Q: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.
A: 遇到valid括号问题,一般使用栈来解决。
遇到左括号,压入栈内;
遇到右括号,如果栈不为空,pop栈(即增加一对有效括号),统计当前有效括号子串长度,同时更新maxlen。统计当前有效括号子串长度,有两种情况:一种是当前栈不为空,curlen = i - stack.top();栈为空时 curlen = i - last;
如果栈为空,说明此时的“(”是最近一个无效的'('
int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function stack<int> st; int last = -1; int maxlen = 0; for(int i=0;i<s.size();i++) { if(s[i]=='(') st.push(i); else{ if(!st.empty()) { st.pop(); if(st.empty()) maxlen = max(maxlen,i-last); else maxlen = max(maxlen,i - st.top()); }else last = i; } } return maxlen; }