链接:https://leetcode.com/problems/longest-valid-parentheses/description/
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"()()"
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
int left_removed = 0;
int right_removed = 0;
for(auto c : s) {
if(c == '(') {
++left_removed;
}
else if(c == ')') {
if(left_removed != 0) {
--left_removed;
}
else {
++right_removed;
}
}
else {
continue;
}
}
return n - left_removed - right_removed;
}
};
首先,想到用栈并不太难。最难的是想到往栈里面存储什么,借助上一题的思路,最直白的想法是存储左括号'(',但是这样做的话,没法解决上面的问题。在网上搜了搜,看到了比较巧妙的办法。即在栈里存储左括号'('的下标index。这样才能正确地计算可能的最长距离。
其次,把问题简化一下,先不找最长的括号串,先找候选括号串。什么是候选括号串呢?需要满足的第一个条件是'('和')'的数量相等(所以,上面提到了使用了栈来进行左右括号是否匹配的检查),需要满足的第二个条件是,匹配的过程中不能出现')('的情况。也就是说,某个时刻,发现有单独的'('出现了,就说明此时此刻的候选串结束了,将开始对新的候选串的检查了。
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> ParenthesesStack;
int maxLen=0;
int lastValiadIndx=0;
for(int indx=0;indx<s.size();indx++)
{
if(s[indx]=='(')//遇到左括号,直接存入
{
ParenthesesStack.push(indx);
}
else //遇到右括号,分情况讨论
{
if(ParenthesesStack.empty()) //如果此时栈里左括号已经被消耗完了,没有额外的左括号用来配对当前的右括号了,那么当前的右括号就被单出来了,表明当前子串可以结束了,此时的右括号也成为了下一个group的分界点,此时右括号下标为index,所以下一个group的起始点为index+1,相当于skip掉当前的右括号
{
lastValiadIndx=indx+1;
}
else //如果此时栈不空,可能有两种情况,1)栈正好剩下1个左括号和当前右括号配对 2)栈剩下不止1个左括号
{
ParenthesesStack.pop();
if(ParenthesesStack.empty()) //栈pop()之前正好剩下1个左括号,pop()之后,栈空了,此时group长度为indx-lastValidIndx
{
maxLen=max(maxLen,indx-lastValiadIndx+1);
}
else //栈有pop()之前剩下不止1个左括号,此时额外多出的左括号使得新的group形成。如()(()())中index=4时,stack中有2个左括号
{
maxLen=max(maxLen,indx-ParenthesesStack.top());
}
}
}
}
return maxLen;
}
};