-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathValidParenthesesSubstring.java
More file actions
34 lines (30 loc) · 1.01 KB
/
ValidParenthesesSubstring.java
File metadata and controls
34 lines (30 loc) · 1.01 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
/*https://leetcode.com/problems/longest-valid-parentheses/*/
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int result = 0, currLen = 0;
for (int i = 0; i < s.length(); ++i)
{
//if open bracket
if (s.charAt(i) == '(')
{
//push the current length and reset it
stack.push(currLen);
currLen = 0;
}
//if closing bracket and stack is not empty
else if (s.charAt(i) == ')' && stack.size() > 0)
{
//add the popped value to 2
currLen += stack.pop() + 2;
//update result
result = Math.max(result,currLen);
}
//if closing bracket and stack is empty
else if (s.charAt(i) == ')' && stack.size() == 0)
//reset current length
currLen = 0;
}
return result;
}
}