/**
* Problem: LeetCode 32 - Longest Valid Parentheses
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int longestValidParentheses(String s) {
int n = s.length();
int[] stack = new int[n + 1];
int top = -1;
int max = 0;
stack[++top] = -1;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '(') {
stack[++top] = i;
} else {
top--;
if (top < 0) {
stack[++top] = i;
} else {
max = Math.max(max, i - stack[top]);
}
}
}
return max;
}
}
"""
Problem: LeetCode 32 - Longest Valid Parentheses
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
class Solution:
def longestValidParentheses(self, s: str) -> int:
stack = [-1]
max_len = 0
for i, c in enumerate(s):
if c == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len
/**
* Problem: LeetCode 32 - Longest Valid Parentheses
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Problem: LeetCode 32 - Longest Valid Parentheses
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length();
vector<int> stack(n + 1);
int top = -1;
int maxLen = 0;
stack[++top] = -1;
for (int i = 0; i < n; i++) {
if (s[i] == '(') {
stack[++top] = i;
} else {
top--;
if (top < 0) {
stack[++top] = i;
} else {
maxLen = max(maxLen, i - stack[top]);
}
}
}
return maxLen;
}
};
/**
* Problem: LeetCode 32 - Longest Valid Parentheses
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var longestValidParentheses = function(s) {
const n = s.length;
const stack = [-1];
let maxLen = 0;
for (let i = 0; i < n; i++) {
if (s[i] === '(') {
stack.push(i);
} else {
stack.pop();
if (stack.length === 0) {
stack.push(i);
} else {
maxLen = Math.max(maxLen, i - stack[stack.length - 1]);
}
}
}
return maxLen;
};