LeetCode 32. Longest Valid Parentheses

Posted 皇家大鹏鹏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 32. Longest Valid Parentheses相关的知识,希望对你有一定的参考价值。

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 "()()"

Seen this question in a real interview before?  

 

这道题比之“验证括号是否有效”要难一些,但是思路类似,也是借助栈,栈中村的是括号的下标,遇到左括号将其下标入栈;遇到右括号将栈定下标弹出并计算有效长度,同时记录下来当前最大长度,这里为了方便起见,我们一开始在栈中放了下标-1,用来表示最开始的位置,时间和空间复杂度都是O(N)

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) {
 4         stack<int> sta;
 5         int maxRes = 0;
 6         sta.push(-1);
 7         for (int i = 0; i < s.size(); i++ )
 8         {
 9             if (s[i] == ()
10                 sta.push(i);
11             else
12             {
13                 sta.pop();
14                 if (sta.empty())
15                     sta.push(i);
16                 else
17                     maxRes = max(maxRes, i - sta.top());
18             }
19         }
20         return maxRes;
21     }
22 };

这道题更详细的解答可以参考官方的solution,还有一种可以在O(1)空间复杂度完成的解法,有些难想,详情可以参考https://leetcode.com/problems/longest-valid-parentheses/solution/#

以上是关于LeetCode 32. Longest Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 32. Longest Valid Parentheses

LeetCode 32. Longest Valid Parentheses

LeetCode 32. Longest Valid Parentheses

[leetcode-32-Longest Valid Parentheses]

leetcode 32. Longest Valid Parentheses

Leetcode 32: Longest Valid Parentheses