1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/java/longest-valid-parentheses.java
Matej Focko 6531d1a35f
java: add «32. Longest Valid Parentheses»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-09-10 12:38:26 +02:00

24 lines
500 B
Java

import java.util.Stack;
class Solution {
public int longestValidParentheses(String s) {
var longest = 0;
var indices = new Stack<Integer>();
indices.push(-1);
for (var i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
indices.push(i);
} else {
indices.pop();
if (indices.isEmpty()) {
indices.push(i);
} else {
longest = Math.max(longest, i - indices.peek());
}
}
}
return longest;
}
}