Skip to content

Commit 9f32925

Browse files
committed
Valid Substring
1 parent 349afe5 commit 9f32925

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

DSA Crack Sheet/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@
157157
- [Sort a stack](https://practice.geeksforgeeks.org/problems/sort-a-stack/1# "view question") - [Cpp Solution](./solutions/Sort%20a%20stack.cpp)
158158
- [Merge Intervals](https://leetcode.com/problems/merge-intervals/ "view question") - [Cpp Solution](./solutions/Merge%20Intervals.cpp)
159159
- [Maximum Rectangular Area in a Histogram](https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1 "view question") - [Cpp Solution](./solutions/Maximum%20Rectangular%20Area%20in%20a%20Histogram.cpp)
160+
- [Valid Substring](https://practice.geeksforgeeks.org/problems/valid-substring0624/1# "view question") - [Cpp Solution](./solutions/Valid%20Substring.cpp)
160161
- []( "view question") - [Cpp Solution](./solutions/.cpp)
161162

162163
### Heap
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Valid Substring
3+
===============
4+
5+
Given a string S consisting only of opening and closing parenthesis 'ie '(' and ')', find out the length of the longest valid(well-formed) parentheses substring.
6+
NOTE: Length of smallest the valid substring ( ) is 2.
7+
8+
Example 1:
9+
Input: S = "(()("
10+
Output: 2
11+
Explanation: The longest valid
12+
substring is "()". Length = 2.
13+
14+
Example 2:
15+
Input: S = "()(())("
16+
Output: 6
17+
Explanation: The longest valid
18+
substring is "()(())". Length = 6.
19+
20+
Your Task:
21+
You dont need to read input or print anything. Complete the function findMaxLen() which takes S as input parameter and returns the maxlength.
22+
23+
Expected Time Complexity:O(n)
24+
Expected Auxiliary Space: O(1)
25+
26+
Constraints:
27+
1 <= |S| <= 105
28+
*/
29+
30+
int findMaxLen(string s)
31+
{
32+
stack<int> si;
33+
si.push(-1);
34+
35+
int ans = 0;
36+
37+
for (int i = 0; i < s.size(); ++i)
38+
{
39+
if (s[i] == '(')
40+
si.push(i);
41+
else
42+
{
43+
si.pop();
44+
if (si.size())
45+
{
46+
int curr = i - si.top();
47+
ans = max(ans, curr);
48+
}
49+
else
50+
si.push(i);
51+
}
52+
}
53+
return ans;
54+
}

0 commit comments

Comments
 (0)