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 "()()"
分析
题目的意思是:求最长的合法括号的长度。
- 遍历整个字符串,遇见左括号,就把左括号的索引压入栈中;如果遇见右括号,这时如果栈为空,说明没有左括号与之配对,则last就从该右括号开始,否则,从栈中取出一个括号,然后计算最大的长度。
C++实现
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stack1;
int res=0;
int start=0;
for(int i=0;i<s.size();i++){
if(s[i]=='('){
stack1.push(i);
}else if(s[i]==')'){
if(stack1.empty()){
start=i+1;
}else{
stack1.pop();
if(stack1.empty()){
res=max(res,i-start+1);
}else{
res=max(res,i-stack1.top());
}
}
}
}
return res;
}
};
Python实现
class Solution:
def longestValidParentheses(self, s: str) -> int:
st = []
res = 0
start = 0
for i in range(len(s)):
if s[i]=='(':
st.append(i)
elif s[i]==')':
if len(st)==0:
start = i+1
else:
st.pop()
if len(st)==0:
res=max(res, i-start+1)
else:
res = max(res,i-st[-1])
return res
参考文献
[编程题]longest-valid-parentheses
[LeetCode] Longest Valid Parentheses 最长有效括号