g0001_0100.s0032_longest_valid_parentheses.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0032_longest_valid_parentheses;
// #Hard #Top_100_Liked_Questions #String #Dynamic_Programming #Stack #Big_O_Time_O(n)_Space_O(1)
// #2023_08_09_Time_1_ms_(100.00%)_Space_41.4_MB_(85.22%)
/**
* 32 - Longest Valid Parentheses\.
*
* Hard
*
* Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring.
*
* **Example 1:**
*
* **Input:** s = "(()"
*
* **Output:** 2
*
* **Explanation:** The longest valid parentheses substring is "()".
*
* **Example 2:**
*
* **Input:** s = ")()())"
*
* **Output:** 4
*
* **Explanation:** The longest valid parentheses substring is "()()".
*
* **Example 3:**
*
* **Input:** s = ""
*
* **Output:** 0
*
* **Constraints:**
*
* * 0 <= s.length <= 3 * 104
* * `s[i]` is `'('`, or `')'`.
**/
public class Solution {
public int longestValidParentheses(String s) {
int max = 0;
int left = 0;
int right = 0;
int n = s.length();
char ch;
for (int i = 0; i < n; i++) {
ch = s.charAt(i);
if (ch == '(') {
left++;
} else {
right++;
}
if (right > left) {
left = 0;
right = 0;
}
if (left == right) {
max = Math.max(max, left + right);
}
}
left = 0;
right = 0;
for (int i = n - 1; i >= 0; i--) {
ch = s.charAt(i);
if (ch == '(') {
left++;
} else {
right++;
}
if (left > right) {
left = 0;
right = 0;
}
if (left == right) {
max = Math.max(max, left + right);
}
}
return max;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy