# Hard-题目36：32. Longest Valid Parentheses

75人阅读 评论(0)

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

For “(()”, the longest valid parentheses substring is “()”, which has length = 2.

Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.

class Solution {
public:
// Using a stack. One pass
int longestValidParentheses(string s) {
vector<int> stack;
int maxLen = 0;
for (int i = 0; i < s.size(); ++i)
{
if (s[i] == '(')
stack.push_back(i);
else {
if (!stack.empty() && s[stack.back()] == '(') {
stack.pop_back();
int lastPos = -1;
if (!stack.empty())
lastPos = stack.back();
int curLen = i - lastPos;
maxLen = (maxLen < curLen) ? curLen : maxLen;
} else
stack.push_back(i);
}
}
return maxLen;
}
};

12ms,15.70%,8ms，43.95%
cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55622次
• 积分：3195
• 等级：
• 排名：第10669名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论