Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
C++
int maxLength(string s) {
stack<int> st;
// Push -1 as the initial index to
// handle the edge case
st.push(-1);
int maxLen = 0;
// Traverse the string
for (int i = 0; i < s.length(); i++) {
// If we encounter an opening parenthesis,
// push its index
if (s[i] == '(') {
st.push(i);
}
else {
// If we encounter a closing parenthesis,
// pop the stack
st.pop();
// If stack is empty, push the current index
// as a base for the next valid substring
if (st.empty()) {
st.push(i);
}
else {
// Update maxLength with the current length
// of the valid parentheses substring
maxLen = max(maxLen, i - st.top());
}
}
}
return maxLen;
}
Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
Commenter avatars come from Gravatar.