32. Longest Valid Parentheses
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.length(), answer = 0;
if(len == 0) return answer;
stack<int> st;
for(int i =0 ; i < len; i++){
if(s[i] == '(') st.push(i);
else if(!st.empty() && s[st.top()]=='(') {
st.pop();
}
else st.push(i);
}
if(st.empty()) return len;
// find longest index gaps in st
int end = len, start = 0; // here end = len is because we need to
// manually figure out the first case : end - start - 1 = # of complete parentheses characters in between two neighboring indices,
// so to be consistent initial position end here is one postition 1 over the last element in the element as if there is an "virtual"
// ')' in the end.
while(!st.empty()){
start = st.top(); st.pop();
answer = max(answer, end - start - 1);
end = start;
}
answer = max(answer, end); // compare the number of parenthesis character skiped till the first index, do not need extra "-1" since
// there is no start index any more (or the "virtual" starting index is at -1)
cout<<end<<endl;
return answer;
}
};Last updated
Was this helpful?