From 6531d1a35f63de596a1f09ab9f5654dd85fa2881 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 10 Sep 2024 12:38:26 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB32.=20Longest=20Valid=20Par?= =?UTF-8?q?entheses=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/longest-valid-parentheses.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 java/longest-valid-parentheses.java diff --git a/java/longest-valid-parentheses.java b/java/longest-valid-parentheses.java new file mode 100644 index 0000000..0e70410 --- /dev/null +++ b/java/longest-valid-parentheses.java @@ -0,0 +1,24 @@ +import java.util.Stack; + +class Solution { + public int longestValidParentheses(String s) { + var longest = 0; + var indices = new Stack(); + + 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; + } +}