Longest Valid Parentheses
Longest Valid Parentheses
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.
最长括号对,采用stack存储左括号的位置,遇到右括号时需要分情况处理,利用一个last变量来存储上一个完整括号对的左边括号的位置。
class Solution { public: int longestValidParentheses(string s) { if(s.size()<2) return 0; int last =-1; stack<int> st; int maxLen =0; for(int i =0; i<s.size();i++){ if(s[i]=='(') st.push(i); else{ if(st.size()==0) last = i; else{ st.pop(); if(st.size()==0){ maxLen = max(maxLen, i-last); } else{ maxLen = max(maxLen,i-st.top()); } } } } return maxLen; } };