-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongestValidSubstring.java
43 lines (38 loc) · 1.16 KB
/
LongestValidSubstring.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
package datastructure.stack.program;
import datastructure.stack.Stack;
/**
* Given a string consisting of opening and closing parenthesis, find length of
* the longest valid parenthesis substring.
*
* @author skedia
*
*/
public class LongestValidSubstring {
public static void main(String[] args) throws Exception {
String a = "((()";
Stack<Character> stack = new Stack<>();
char[] arr = a.toCharArray();
int result = 0;
int curr = 0;
for (Character c : arr) {
if (c == '(') {
// If open parenthesis is encountered then push it onto the
// stack
stack.push(c);
} else if (stack.peek() != null) {
// if stack has elements and close parenthesis is encountered
// then pop the stack and increment current by 2
stack.pop();
curr += 2;
} else {
// if stack is empty and close parenthesis is encountered that
// means end of valid substring. make current equals zero
curr = 0;
}
// if current is greater than result then assign the same to result.
result = (result > curr) ? result : curr;
}
// print the result out.
System.out.println("length: " + result);
}
}