fork download
  1. // C++ program to find length of the
  2. // longest valid substring
  3.  
  4. #include <iostream>
  5. #include <stack>
  6. using namespace std;
  7.  
  8. int maxLength(string s) {
  9. stack<int> st;
  10.  
  11. // Push -1 as the initial index to
  12. // handle the edge case
  13. st.push(-1);
  14. int maxLen = 0;
  15. int curr = 0;
  16.  
  17. // Traverse the string
  18. for (int i = 0; i < s.length(); i++) {
  19.  
  20. // If we encounter an opening parenthesis,
  21. // push its index
  22. if (s[i] == '(') {
  23. st.push(i);
  24. } else {
  25.  
  26. // If we encounter a closing parenthesis,
  27. // pop the stack
  28. st.pop();
  29.  
  30. // If stack is empty, push the current index
  31. // as a base for the next valid substring
  32. if (st.empty()) {
  33. st.push(i);
  34. curr = 0;
  35. } else {
  36. curr += 2;
  37. cout << curr << ' ' << i - st.top() << '\n';
  38. // Update maxLength with the current length
  39. // of the valid parentheses substring
  40. maxLen = max(maxLen, i - st.top());
  41. }
  42. }
  43. }
  44.  
  45. return maxLen;
  46. }
  47.  
  48. int main() {
  49. string s = "(())))()())()()(()(()(()))(()(())(()(())(())((()())))())()()(()())(((())))(())()))())(((()((()(((()((((())()(((((()()(()(((())(((())((((())((()(((())))()()))()))()(())((((((()())(()))()()(()(())))((()()(()(((((())))(((()()((()))()(()(())(((())))))";
  50. cout << maxLength(s) << endl;
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
2 2
4 4
2 2
4 4
2 2
4 4
6 2
8 2
10 2
12 6
14 10
16 2
18 2
20 6
22 2
24 2
26 6
28 2
30 10
32 2
34 4
36 6
38 18
40 26
42 28
44 40
46 42
48 44
50 2
52 4
54 50
56 2
58 4
60 6
62 58
64 2
66 62
68 64
70 70
2 2
2 2
4 2
6 2
8 2
10 4
12 6
14 2
16 4
18 2
20 2
22 4
24 2
26 4
28 2
30 4
32 2
34 2
36 4
38 6
40 10
42 12
44 14
46 16
48 22
50 24
52 26
54 28
56 30
58 2
60 34
62 2
64 4
66 6
68 2
70 10
72 12
74 14
76 16
78 2
80 2
82 6
84 24
86 26
88 2
90 4
92 2
94 2
96 4
98 6
100 8
102 2
104 4
106 2
108 4
110 10
112 12
114 2
116 2
118 6
120 2
122 4
124 6
126 14
128 28
130 30
70