Appearance
32. Longest Valid Parentheses
https://leetcode.com/problems/longest-valid-parentheses/
c++
class Solution {
public:
int longestValidParentheses(string s) {
int result = 0;
stack<int> stk;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ')' && !stk.empty() && s[stk.top()] == '(') {
stk.pop();
if (stk.empty()) {
result = i + 1;
} else {
result = max(result, i - stk.top());
}
} else {
stk.push(i);
}
}
return result;
}
};
go
func longestValidParentheses(s string) int {
result := 0
stack := []int{}
for i, c := range s {
if c == ')' && len(stack) > 0 && s[stack[len(stack) - 1]] == '(' {
stack = stack[0:len(stack)-1]
if len(stack) > 0 {
if i - stack[len(stack)-1] > result {
result = i - stack[len(stack)-1]
}
} else {
result = i + 1
}
} else {
stack = append(stack, i)
}
}
return result
}
js
/**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function(s) {
var result = 0
var stack = []
for (let i = 0; i < s.length; i++) {
if (s[i] === ')' && stack.length && s[stack[stack.length - 1]] === '(') {
stack.pop()
if (stack.length) {
result = Math.max(result, i - stack[stack.length - 1])
} else {
result = i + 1
}
} else {
stack.push(i)
}
}
return result
}
py
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
result, stack = 0, []
for i, c in enumerate(s):
if c == ')' and len(stack) > 0 and s[stack[-1]] == '(':
stack.pop()
if len(stack) > 0:
result = max(result, i - stack[-1])
else:
result = i + 1
else:
stack.append(i)
return result