forked from garvit-bhardwaj/Leetcode-Problems-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate Longest Valid Parentheses.cpp
48 lines (45 loc) · 1.28 KB
/
Create Longest Valid Parentheses.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
int longestValidParentheses(string s) {
int open=0, close=0;
int maxLen=0;
//traversing from left
for(int i=0;i<s.size();i++){
if(s[i]=='('){
open++;
}
else{
close++;
}
//valid pair of paranthesis if number of opening and closing brackets are equal
if(open==close){
int len=open+close;
maxLen=max(maxLen,len);
}
else if(close>open){ //from left if closing brackets is greater than openin brackets
close=0;
open=0;
}
}
open=0,close=0;
//traversing from right
for(int i=s.size()-1;i>=0;i--){
if(s[i]=='('){
open++;
}
else{
close++;
}
//valid pair of paranthesis if number of opening and closing brackets are equal
if(open==close){
int len=open+close;
maxLen=max(maxLen,len);
}
else if(close<open){ //from right if opening brackets is greater than closing brackets
close=0;
open=0;
}
}
return maxLen;
}
};