#Leetcode# 32. Longest Valid Parentheses
https://leetcode.com/problems/longest-valid-parentheses/
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is"()()"
代码:
class Solution {
public:
int longestValidParentheses(string s) {
int ans = 0, start = 0;
stack<int> m;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(') m.push(i);
else if (s[i] == ')') {
if (m.empty()) start = i + 1;
else {
m.pop();
if(m.empty())
ans = max(ans, i - start + 1);
else ans = max(ans, i - m.top());
}
}
}
return ans;
}
};
最长有效括号
更多精彩

