leetcode:Longest Valid Parentheses
2014-07-06 15:54
288 查看
Given a string containing just the characters
find the length of the longest valid (well-formed) parentheses substring.
For
which has length = 2.
Another example is
parentheses substring is
4.
'('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: int longestValidParentheses(string s) { stack< int> stk;//记录左括号的下标 int max_length = 0; int last_match = -1;//记录上一个")"的下标 for( int i = 0; i < s.size(); ++i){ if( s[i] == '(') stk.push(i); else{ if( !stk.empty()){ stk.pop();//两个括号匹配,出栈 if( !stk.empty())//如果不为空,右括号一直是跟栈顶的左括号匹配,也就是未匹配左括号中最右的括号 max_length = max( max_length, i - stk.top());//所以这里更新长度,是i-stk.top() else//一次有效匹配结束 max_length = max( max_length, i - last_match); } else last_match = i; } } return max_length; } };
相关文章推荐
- LeetCode Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- leetcode problem 32 -- Longest Valid Parentheses
- leetcode Longest Valid Parentheses python
- Leetcode:Longest Valid Parentheses
- LeetCode 32 - Longest Valid Parentheses
- leetcode32 Longest Valid Parentheses 最长有效括号序列
- LeetCode Longest Valid Parentheses
- [Leetcode] longest valid parentheses 最长的有效括号
- LeetCode 032 Longest Valid Parentheses
- leetcode 32 Longest Valid Parentheses
- Leetcode 32. Longest Valid Parentheses
- LeetCode 32 Longest Valid Parentheses(最长有效括号)(*)
- [leetcode刷题系列]Longest Valid Parentheses
- (Java)LeetCode-32. Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- leetcode 032 Longest Valid Parentheses
- Leetcode之Longest Valid Parentheses
- Leetcode: Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses 最长有效括号