Problem
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
Solution: Stack
Use a stack to track the index of all unmatched open parentheses.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: int longestValidParentheses(string s) { stack<int> q; int start = 0; int ans = 0; for (int i = 0;i < s.length(); i++) { if(s[i] == '(') { q.push(i); } else { if (q.empty()) { start = i + 1; } else { int index = q.top(); q.pop(); ans = max(ans, q.empty() ? i - start + 1 : i - q.top()); } } } return ans; } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Author: Huahua class Solution: def longestValidParentheses(self, s): q = [] start, ans = 0, 0 for i in range(len(s)): if s[i] == '(': q.append(i) continue if not q: start = i + 1 else: q.pop() ans = max(ans, i - q[-1] if q else i - start + 1) return ans |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment