[Leetcode] Longest Valid Parentheses
2013-02-22 04:55
441 查看
Given a string containing just the characters
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.
'('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.
#include <stack> using namespace std; class Solution { public: int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int maxLength = 0; int size = s.size(); stack<int> left; if(size<=0) return 0; int top = size; for(int i = 0; i<size; i++) { if(s[i]=='(') { left.push(i); } else { if(left.empty()) { top = i + 1;//指向下一个为")"的index } else { int tmp = left.top(); top = min(top,tmp); left.pop(); if(left.empty()) maxLength = max(i-top+1,maxLength); else maxLength = max(i-left.top(),maxLength); //注意:为什么是left.top()而不是tmp-1呢?考虑"(()()"的情况。 } } } return maxLength; } };
相关文章推荐
- leetcode Longest Valid Parentheses
- LeetCode 32 Longest Valid Parentheses
- leetcode 32 : Longest Valid Parentheses
- Leetcode-Longest Valid Parentheses
- leetcode--Longest Valid Parentheses
- LeetCode 32 Longest Valid Parentheses
- leetcode:Longest Valid Parentheses
- [leetcode刷题系列]Longest Valid Parentheses
- [leetcode]Longest Valid Parentheses
- leetcode 32: Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses, Solution
- LeetCode Longest Valid Parentheses 解题报告
- 【Leetcode】Longest Valid Parentheses
- leetcode 32.Longest Valid Parentheses
- LeetCode - Longest Valid Parentheses
- leetcode习题解答:32. Longest Valid Parentheses
- LeetCode - 32 -Longest Valid Parentheses.md
- leetcode Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses