LeetCode: Longest Valid Parentheses
2012-10-07 17:19
387 查看
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.
class Solution { public: int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int nSize = s.size(); if (nSize <= 1) return 0; stack<int> pare; int longest = 0; int top = nSize; for (int i = 0; i < nSize; ++i) { if (s[i] == '(') pare.push(i); else if(!pare.empty()) { int tmp = pare.top(); pare.pop(); top = top < tmp ? top : tmp; if (pare.empty()) longest = longest > i - top + 1 ? longest : i - top + 1; else longest = longest > i - pare.top() ? longest : i - pare.top(); } else top = i + 1; } return longest; } };
相关文章推荐
- leetcode:Longest Valid Parentheses 使用动态规划O(n)思路
- leetcode第一刷_Longest Valid Parentheses
- LeetCode题解:Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses [031]
- leetcode 032 —— Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses 最长有效括号
- [leetcode]Longest Valid Parentheses
- leetcode: Longest Valid Parentheses
- leetcode - Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode 32. Longest Valid Parentheses
- LeetCode 121 Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- Longest Valid Parentheses -- leetcode
- leetcode: Longest Valid Parentheses
- 49_leetcode_Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- leetcode: Longest Valid Parentheses
- LeetCode题目:32. Longest Valid Parentheses
- [leetcode] Longest Valid Parentheses