-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLengthSubstring.java
63 lines (51 loc) · 1.59 KB
/
LengthSubstring.java
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
package Stack;
public class LengthSubstring {
static int findMaxLen(String str)
{
int n = str.length();
// Create a stack and push -1
// as initial index to it.
Stack<Integer> stk = new Stack<>();
stk.push(-1);
// Initialize result
int result = 0;
// Traverse all characters of given string
for (int i = 0; i < n; i++)
{
// If opening bracket, push index of it
if (str.charAt(i) == '(')
stk.push(i);
// // If closing bracket, i.e.,str[i] = ')'
else
{
// Pop the previous
// opening bracket's index
if(!stk.empty())
stk.pop();
// Check if this length
// formed with base of
// current valid substring
// is more than max
// so far
if (!stk.empty())
result
= Math.max(result,
i - stk.peek());
// If stack is empty. push
// current index as base
// for next valid substring (if any)
else
stk.push(i);
}
}
return result;
}
public static void main(String[] args) {
String str = "((()()";
// Function call
System.out.println(findMaxLen(str));
str = "()(()))))";
// Function call
System.out.println(findMaxLen(str));
}
}