# LeetCode:Longest Valid Parentheses

3023人阅读 评论(1)

### Longest Valid Parentheses

Total Accepted: 63715 Total Submissions: 282480 Difficulty: Hard

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.

Subscribe to see which companies asked this question

c++ code:

class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length();
stack<int> st;
for (int i = 0; i < n; i++) {
if (s[i] == '(') st.push(i);
else {
if (!st.empty()) {
if (s[st.top()] == '(') st.pop();
else st.push(i);
}
else st.push(i);
}
}

int a = n, b = 0;
int ans = 0;
while(!st.empty()) {
b = st.top();
st.pop();
ans = max(ans, a-b-1);
a = b;
}
ans = max(ans, a);
return ans;
}
};

0
0

个人资料
• 访问：390374次
• 积分：6789
• 等级：
• 排名：第4136名
• 原创：321篇
• 转载：1篇
• 译文：0篇
• 评论：34条
博客专栏
 FFmpeg4Android 文章：7篇 阅读：834
 LeetCode解题记录 文章：215篇 阅读：275684
 Java源码解析 文章：12篇 阅读：12969
阅读排行
最新评论
个人收藏
友情链接