mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «32. Longest Valid Parentheses»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
dcefa07684
commit
6531d1a35f
1 changed files with 24 additions and 0 deletions
24
java/longest-valid-parentheses.java
Normal file
24
java/longest-valid-parentheses.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue