点击(此处)折叠或打开
- int longestValidParentheses(string s){
- stack<int> st;
- int start=-1, len=s.length();
- int res=0;
- for(int i=0; i<len; i++){
- if(s[i]=='(')st.push(i);// 左括号下标入栈,防止算多
- else{
- if(st.empty())start=i;// 弹出非法才会更新start
- else{
- st.pop();
- if(st.empty())res=max(res,i-start);// 为空,则(start,i]满足全匹配
- else res=max(res,i-st.top());// 若不为空,则(st.top,i]满足全匹配
- }
- }
- }
- return res;
- }