题目:给一个只包含‘(’和‘)’的字符串,寻找最大的合法的闭合结构
思路:依然是滑动窗口法,不过需要利用一个栈,当遇到‘(’则入栈,遇到‘)’时,如果栈为空,则左边界需要移动到当前位置,否则出栈一次,同时判断当前位置和左边界距离是否大于max,此时需要考虑出栈一次后栈是否为空,如果为空,说明当前位置到左边界之间为合法的闭合结构,否则说明栈顶元素的位置到当前位置为合法的闭合结构。
class Solution {
public:
int longestValidParentheses(string s) {
int length=s.size();
if(length==0||length==1)return 0;
stack<int> location;
int max=0;
int i;
int left=-1;
for(i=0;i<length;i++){
if(s[i]=='(')location.push(i);
else{
if(location.empty())left=i;
else{
location.pop();
if(location.empty())max=(max>(i-left))?max:i-left;
else
max=(max>(i-location.top()))?max:i-location.top();
}
}
}
return max;
}
};