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

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的碎碎念：

#### LeetCode --- 32. Longest Valid Parentheses

2015-02-04 23:16:46

#### LeetCode 32 Longest Valid Parentheses (C,C++,Java,Python)

2015-05-14 17:16:32

#### LeetCode(32)Longest Valid Parentheses

2014-03-07 08:31:54

#### [Leetcode]32. Longest Valid Parentheses @python

2016-01-17 11:30:43

#### Leetcode 32 Longest Valid Parentheses DP好题

2016-09-05 13:43:45

#### 32. Longest Valid Parentheses

2015-07-13 20:41:12

#### Longest Valid Parentheses,二维动态规划、一维动态规划、stack

2014-12-10 10:31:34

#### 32. Longest Valid Parentheses 动态规划解法

2017-12-05 22:08:08

#### LeetCode Longest Valid Parentheses 解题报告

2014-09-22 00:24:27

#### Leetcode——32. Longest Valid Parentheses

2017-05-21 23:24:38