[leetcode] 32. 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 "()()"

分析

题目的意思是:求最长的合法括号的长度。

  • 遍历整个字符串,遇见左括号,就把左括号的索引压入栈中;如果遇见右括号,这时如果栈为空,说明没有左括号与之配对,则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 最长有效括号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值