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