题目:
解题流程:
1.需有一个变量start记录有效括号子串的起始下标,max表示最长有效括号子串长度,初始值均为0
2.遍历给字符串中的所有字符
2.1若当前字符s[index]为左括号'(',将当前字符下标index入栈(下标稍后有其他用处),处理下一字符
2.2若当前字符s[index]为右括号')',判断当前栈是否为空
2.2.1若栈为空,则start = index + 1,处理下一字符(当前字符右括号下标不入栈)
2.2.2若栈不为空,则出栈(由于仅左括号入栈,则出栈元素对应的字符一定为左括号,可与当前字符右括号配对),判断栈是否为空
2.2.2.1若栈为空,则max = max(max, index-start+1)
2.2.2.2若栈不为空,则max = max(max, index-栈顶元素值)
python3代码如下:
class Solution:
def longestValidParentheses(self, s: str) -> int:
nstack = []
start = 0
maxlen = 0
for i in range(len(s)):
if s[i] == '(':
nstack.append(i)
else:
if len(nstack) == 0:
start = i + 1
else:
nstack.pop()
if len(nstack) == 0:
maxlen = max(maxlen, i - start + 1)
else:
maxlen = max(maxlen, i - nstack[-1])
return maxlen
执行结果:
C++代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> nstack;
int maxlen = 0;
int start = 0;
for(int i=0; i<s.length(); i++){
if(s[i] == '('){
nstack.push(i);
}
else{
if(nstack.empty()){
start = i + 1;
}
else{
nstack.pop();
if(nstack.empty()){
maxlen = max(maxlen, i - start + 1);
}
else{
maxlen = max(maxlen, i - nstack.top());
}
}
}
}
return maxlen;
}
};
执行结果:
参考链接:
https://blog.csdn.net/weixin_38823568/article/details/80997966