LeetCode——Longest Valid Parentheses

本文介绍了一种使用辅助数组和栈解决最长有效括号子串问题的方法。通过遍历字符串,利用栈来记录左括号的位置,并计算以每个右括号结尾的最长有效括号子串的长度。

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.

» Solve this problem


采用辅助数组length,length[i]表示以i结尾最长的合法字符串的长度。

那么对于一对括号( ),假设(在第j位,)在第k位,如果它们能匹配,则length[k] = length[j - 1] + (k - j + 1)。

用一个堆栈来模拟括号匹配。


class Solution {
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int ans = 0;
        stack<int> stacks;
        int length[s.size()];
        memset(length, 0, sizeof(int) * s.size());
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') {
                stacks.push(i);
            }
            else if (s[i] == ')') {
                if (!stacks.empty()) {
                    int idx = stacks.top();
                    length[i] = i - idx + 1 + (idx > 0 ? length[idx - 1] : 0);
                    if (length[i] > ans) {
                        ans = length[i];
                    }                     
                    stacks.pop();
                }
            }
        }
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值