classSolution { public: intlongestValidParentheses(string s) { int ans = 0; int n = s.length(); int index; stack<bool> sta; for (int i = 0; i < n; i++) { index = i; while (index < n) { if (s[index] == '(') { sta.push(true); } else { if (sta.empty()) { break; } else { sta.pop();
} } index++; if (sta.empty()) { ans = max(ans, index - i); } } if (sta.empty()) { } else { while (!sta.empty()) { sta.pop(); } } }
return ans; } };
栈
思路分析
遇(入栈,遇)出栈,出栈时更新
1.出栈后,栈为空,ans = max(ans, index - startindex + 1)
2.出站后,栈不为空,max(ans, index - sta.top())
执行用时 :16 ms, 在所有 C++ 提交中击败了13.58%的用户 内存消耗 :7.2 MB, 在所有 C++ 提交中击败了100.00%的用户
classSolution { public: intlongestValidParentheses(string s) { int ans = 0; int n = s.length(); int index = 0; int startindex = 0; int top; stack<int> sta;
while (index < n) { if (s[index] == '(') { sta.push(index); } else { if (sta.empty()) { startindex = index + 1; } else { top = sta.top(); sta.pop(); if (sta.empty()) { ans = max(ans, index - startindex + 1); } else { ans = max(ans, index - sta.top()); }
在这种方法中,我们利用两个计数器 leftleft 和 rightright 。首先,我们从左到右遍历字符串,对于遇到的每个 ‘(’,我们增加 left 计算器,对于遇到的每个 ‘)’ ,我们增加 right 计数器。每当 left 计数器与 right 计数器相等时,我们计算当前有效字符串的长度,并且记录目前为止找到的最长子字符串。如果 right 计数器比 left 计数器大时,我们将 left 和 right 计数器同时变回 0.
classSolution { public: intlongestValidParentheses(string s) { int ans = 0; int n = s.length(); int left = 0, right = 0; for (int i = 0; i < n; i++) { if (s[i] == '(') { left++; } else { right++; if (left == right) { ans = max(ans, left + right); } elseif (left < right) { left = 0; right = 0; } } } left = 0; right = 0; for (int i = n - 1; i >= 0; i--) { if (s[i] == ')') { right++; } else { left++; if (left == right) { ans = max(ans, left + left); } elseif (right < left) { left = 0; right = 0; } } } return ans; } };