32. 最长有效括号
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例 1:
输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"
示例 2:
输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
示例 3:
输入:s = ""
输出:0
#include<iostream>
#include<stack>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
/*
用栈来求解,返回结果res,还需要用个变量 start 来记录合法括号串的起始位置,
遍历字符串,如果遇到左括号,则将当前下标压入栈,
如果遇到右括号,如果当前栈为空,则将下一个坐标位置记录到 start,
如果栈不为空,则将栈顶元素取出,此时若栈为空,则更新结果和 i - start + 1 中的较大值,
否则更新结果和 i - st.top() 中的较大值
比如“(()”res =i - st.top()
*/
class Solution {
public:
int longestValidParentheses(string s)
{
int res = 0;
int start = 0;
int n = s.size();
stack<int> st;
for (int i = 0; i < n; ++i) {
if (s[i] == '(')
{
st.push(i);
}
else if (s[i] == ')')
{
if (st.empty())
{
start = i + 1;
}
else
{
st.pop();
res = st.empty() ? max(res, i - start + 1) : max(res, i - st.top());
}
}
}
return res;
}
};
int main()
{
string s1;
getline(cin, s1);
int ans = Solution().longestValidParentheses(s1);
cout << ans << endl;
system("pause");
return 0;
}
python版本
def solution(str1:str)->int:
#记录左括号的索引
gost=[]
# 记录右括号的索引
man=[]
for index in range(len(str1)):
if str1[index]=='(':
gost.append(index)
elif str1[index]==')':
#当遇到一个右括号时就 分别 消除 左括号、右括号的最后一个
man.append(index)
if gost:
gost.pop(-1)
man.pop(-1)
#遍历下来 gost 里是未匹配 左括号的索引数组 man 里是未匹配 右括号的索引数组
#将其融合起来
# 以 未匹配的 括号索引 将原字符串 进行分组, 最大的 子字符串长度 就是 所求 长度
lensum=len(gost)+len(man)
result=[]
index1=index2=0
print("gost",gost)
print("man",man)
while len(result)!=lensum:
if index1<len(gost) and index2<len(man):
if gost[index1]<man[index2]:
result.append(gost[index1])
index1 +=1
else:
result.append(man[index2])
index2 += 1
elif index1<len(gost):
result.append(gost[index1])
index1 += 1
elif index2 < len(man):
result.append(man[index2])
index2 += 1
else:
break
print('result : ',result)
if len(result)==0:
print(len(str1))
return
if result[0] !=0:
result.insert(0,0)
if result[-1]!=len(str1)-1:
result.append(len(str1)-1)
print(result)
maxnum=0
for i in range(len(result)-1):
if result[i+1]-result[i]!=1:
if maxnum<result[i+1]-result[i]:
maxnum=result[i+1]-result[i]
if maxnum %2==1:
maxnum -=1
return maxnum
浙公网安备 33010602011771号