-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParenthesisSubString.java
More file actions
45 lines (33 loc) · 1.1 KB
/
Copy pathLongestValidParenthesisSubString.java
File metadata and controls
45 lines (33 loc) · 1.1 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
import java.util.*;
public class LongestValidParenthesisSubString {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int maxLength = 0;
int lastInvalid = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if (stack.isEmpty()) {
lastInvalid = i;
} else {
stack.pop();
if (stack.isEmpty()) {
maxLength = Math.max(maxLength, i - lastInvalid);
} else {
maxLength = Math.max(maxLength, i - stack.peek());
}
}
}
}
return maxLength;
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the parentheses to check!!");
String str= sc.nextLine();
LongestValidParenthesisSubString ob= new LongestValidParenthesisSubString();
int res=ob.longestValidParentheses(str);
System.out.println(res);
}
}