java: add «32. Longest Valid Parentheses»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-10 12:38:26 +02:00
parent dcefa07684
commit 6531d1a35f
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,24 @@
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;
}
}