-
Notifications
You must be signed in to change notification settings - Fork 1
/
Valid_Substring.cpp
69 lines (53 loc) · 1.67 KB
/
Valid_Substring.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
66
67
68
69
/*
Problem Statement:
------------------
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.
NOTE: Length of smallest the valid substring ( ) is 2.
Example 1:
----------
Input: S = "(()("
Output: 2
Explanation: The longest valid substring is "()". Length = 2.
Example 2:
----------
Input: S = "()(())("
Output: 6
Explanation: The longest valid substring is "()(())". Length = 6.
Your Task: You dont need to read input or print anything. Complete the function findMaxLen() which takes S as input parameter and returns the maxlength.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
*/
// Link --> https://practice.geeksforgeeks.org/problems/valid-substring0624/1
// Code:
class Solution
{
public:
int findMaxLen(string s)
{
int start = 0, end = 0 , answer = 0;
for (int i=0 ; i<s.size() ; i++)
{
if (s[i] == '(')
start++;
else
end++;
if(start == end)
answer = max(answer , (start + end));
else if(end > start)
start = end = 0;
}
start = end = 0;
for (int i=s.size() - 1 ; i>=0 ; i--)
{
if (s[i] == '(')
start++;
else
end++;
if(start == end)
answer = max(answer , (start + end));
else if(start > end)
start = end = 0;
}
return answer;
}
};