Skip to content

Commit

Permalink
Merge pull request #89 from Shrut012/patch-3
Browse files Browse the repository at this point in the history
Longest Valid Parentheses.cpp
  • Loading branch information
avastino7 authored Nov 1, 2022
2 parents ed2050d + a21a065 commit 3f30d81
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Longest Valid Parentheses.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
*/

class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
stk.push(-1);
int maxL=0;
for(int i=0;i<s.size();i++)
{
int t=stk.top();
if(t!=-1&&s[i]==')'&&s[t]=='(')
{
stk.pop();
maxL=max(maxL,i-stk.top());
}
else
stk.push(i);
}
return maxL;
}
};

0 comments on commit 3f30d81

Please sign in to comment.