-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #89 from Shrut012/patch-3
Longest Valid Parentheses.cpp
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |