LeetCode Algorithms 32. Longest Valid Parentheses

题目难度: Hard


原题描述:

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.


题目大意:

        给你一个只包含"("和")"的字符串,让你找出最长的匹配的子串,输出其长度。


解题思路:

        一开始以为是简单的括号匹配,取其中最长的一段匹配的子串就行了。但是后来发现没那么简单,难点在于如何判断当前扫描到的字符是属于之前的一个未匹配完的匹配串的一部分还是新的匹配串的一部分。我在这个问题上想了很久,用代码尝试去实现但是发现始终有测试数据过不了。后来听到了同学的一个方法:用一个数组将匹配的括号的位置标记为true,然后扫描一遍数组,找出连续为true的最大长度,这个就是匹配串的最大长度。


时间复杂度分析:

        算法使用栈来匹配括号,这需要扫描一遍原字符串,时间复杂度为O(n),n为字符串的长度,最后还要扫描一遍记录匹配字符的位置的数组,时间复杂度也是O(n)。因此总的时间复杂度为O(n)。


以下是代码:

class Solution {
public:
    int longestValidParentheses(string s) {
        const int maxLen = 100000;
    bool match[maxLen];
    memset(match,0,sizeof(match));
    stack <char> st1;
    stack <int> st2;
    int i;
    for(i=0 ; s[i]!='\0' ; ++i){
        if(s[i]=='('){
            st1.push(s[i]);
            st2.push(i);
        }
        else{
            if(st1.empty())
                continue;
            match[i] = true;
            match[st2.top()] = true;
            st1.pop();
            st2.pop();
        }
    }

    int cnt=0;
    int ans = 0;
    for(i=0 ; i<s.size() ; ++i){
        if(match[i]){
            ++cnt;
        }else{
            ans = (ans>cnt ? ans : cnt);
            cnt = 0;
        }
    }
    ans = (ans>cnt ? ans : cnt);
    return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值