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)

类似的题目有Valid ParenthesesGenerate Parentheses

 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/#

posted @ 2018-10-27 22:42  皇家大鹏鹏  阅读(175)  评论(0编辑  收藏  举报