1 class Solution { 2 public: 3 int longestValidParentheses(string s) { 4 int n = s.length(), longest = 0; 5 stack<int> st; 6 for (int i = 0; i < n; i++) { 7 if (s[i] == '(') st.push(i); 8 else { 9 if (!st.empty()) { 10 if (s[st.top()] == '(') st.pop(); 11 else st.push(i); 12 } 13 else st.push(i); 14 } 15 } 16 if (st.empty()) longest = n; 17 else { 18 int a = n, b = 0; 19 while (!st.empty()) { 20 b = st.top(); st.pop(); 21 longest = max(longest, a-b-1); 22 a = b; 23 } 24 longest = max(longest, a); 25 } 26 return longest; 27 } 28 };
参考:https://leetcode.com/problems/longest-valid-parentheses/discuss/14126/My-O(n)-solution-using-a-stack
补充一个python的实现:
1 class Solution: 2 def longestValidParentheses(self, s: str) -> int: 3 n = len(s) 4 longest = 0 5 st = [] 6 for i in range(n): 7 if s[i] == '(': 8 st.append(i) 9 else:#s[i] == ')' 10 if len(st) > 0 and s[st[-1]] == '(':#前一位置是'(' 11 st.pop(-1)#获得一个合法匹配 12 else: 13 st.append(i) 14 if len(st) == 0:#s所有字符都是合法括号对 15 longest = n 16 else: 17 a,b = n,0 18 while len(st) != 0:#st中记录的都是无法匹配的'('和')'出现的位置,可称为'单身括号' 19 b = st.pop(-1) 20 longest = max(longest,a-b-1)#计算当前'单身括号'与下一个'单身括号'的距离,就是最长合法substring(连续子串)的长度 21 a = b 22 longest = max(longest,a) 23 return longest