-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParenthesis.java
More file actions
61 lines (50 loc) · 1.55 KB
/
LongestValidParenthesis.java
File metadata and controls
61 lines (50 loc) · 1.55 KB
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
package Stacks;
import java.util.Stack;
public class LongestValidParenthesis {
public static int findMaxLen(String str) {
int n = str.length();
Stack<Integer> stk = new Stack<>();
stk.push(-1);
int result = 0;
for (int i = 0; i < n; i++) {
if (str.charAt(i) == '(')
stk.push(i);
else {
if (!stk.empty())
stk.pop();
if (!stk.empty())
result = Math.max(result, i - stk.peek());
else
stk.push(i);
}
}
return result;
}
public static int findMaxLenTwo(String s, int n) {
int left = 0, right = 0;
int maxLength = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '(') left++;
else right++;
if (left == right)
maxLength = Math.max(maxLength, 2 * right);
else if (right > left)
left = right = 0;
}
left = right = 0;
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == '(') left++;
else right++;
if (left == right)
maxLength = Math.max(maxLength, 2 * left);
else if (left > right)
left = right = 0;
}
return maxLength;
}
public static void main(String[] args) {
// Function call
System.out.println(findMaxLen("((()()()()(((())"));
System.out.println(findMaxLenTwo("((()()()()(((())", 16));
}
}