-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlongest_valid_paramtheses.cpp
65 lines (55 loc) · 1.38 KB
/
longest_valid_paramtheses.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Longest valid Parentheses
/*
Given a string str consisting of opening and closing parenthesis '(' and ')'.
Find length of the longest valid parenthesis substring.
A parenthesis string is valid if:
- For every opening parenthesis, there is a closing parenthesis.
- Opening parenthesis must be closed in the correct order.
Example1:
Input: ((()
Output: 2
Explaination: The longest valid parenthesis substring is "()".
Example2:
Input: )()())
Output: 4
Explaination: The longest valid parenthesis substring is "()()".
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ |str| ≤ 10^5
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxLength(string& str) {
stack<int> stk;
stk.push(-1);
int n = str.length();
int maxLen = 0;
for(int i = 0; i < n; ++i) {
if(str[i] == '(')
stk.push(i);
else {
stk.pop();
if(stk.empty())
stk.push(i);
else {
maxLen = max(maxLen, i - stk.top());
}
}
}
return maxLen;
}
};
int main() {
int t;
cin >> t;
while (t--) {
string S;
cin >> S;
Solution ob;
cout << ob.maxLength(S) << "\n";
}
return 0;
}