LeetCode 32:Longest Valid Parentheses

70 篇文章 1 订阅
39 篇文章 0 订阅

题目链接:

https://leetcode.com/problems/longest-valid-parentheses/description/

描述

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

For “(()”, the longest valid parentheses substring is “()”, which has length = 2.

Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.

输入

输入一个只有小括号的字符串。

输出

输出其连续匹配的最大长度。

样例输入

”)()())”
“)()(()”

样例输出

4
2

算法思想:

这道题使用了一个技巧,就是压栈压入的是字符串的小标,而不压入字母本身。当是左括号时,就压栈(压入的是其下表),如果是右括号且栈为空时,起始位置为当前的下标,否则,弹栈,之后再判断栈是否为空,后续操作。

源代码

class Solution {
public:
    int S[100000];
    int longestValidParentheses(string s) {
        int len = s.length();
        int sta = -1, cnt = 0, ans = 0, k = 0;
        for (int i = 0; i < len; i++)
        {
            if (s[i] == '(')
            {
                S[k++] = i;
            }
            else
            {
                if (k == 0) sta = i;
                else
                {
                    k--;
                    if (k == 0) ans = max(ans, i - sta);
                    else
                        ans = max(ans,i - S[k - 1]);
                }
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值