Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.html
Example 1:this
Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()"
Example 2:spa
Input: "" Output: 4 Explanation: The longest valid parentheses substring is )()())"()()"
Seen this question in a real interview before? code
这道题比之“验证括号是否有效”要难一些,可是思路相似,也是借助栈,栈中村的是括号的下标,遇到左括号将其下标入栈;遇到右括号将栈定下标弹出并计算有效长度,同时记录下来当前最大长度,这里为了方便起见,咱们一开始在栈中放了下标-1,用来表示最开始的位置,时间和空间复杂度都是O(N)orm
相似的题目有Valid Parentheses,Generate Parentheseshtm
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/#blog