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.

解题思路:利用stack在扫描字符串的过程中判断合法的子字符串的区间并保存起来,接下来要做的便是利用O(n)的时间复杂度合并区间,由于stack的关系,大区间的索引肯定在小区间的后面,这样我们从后往前标记区间便可以实现O(n)的时间复杂度,最终求解最长的区间即可,算法总的时间复杂度是O(n)的。

class Solution {
public:
    int longestValidParentheses(string s) {
        int ans = 0, cnt = 0;
        int sp, ep;
        int size = s.length();
        stack<int> stk;
        vector< pair<int,int> > vec;
        bool mark[100010];
        memset(mark, false, sizeof(mark));
        for(int i = 0; i < size; ++i) {
            if(s[i] == ')') {
                if(stk.empty()) {
                    continue;
                } else {
                    vec.push_back(make_pair(stk.top(), i));
                    stk.pop();
                }
            } else {
                stk.push(i);
            }
        }
        size = vec.size();
        for(int i = size - 1; i >= 0; --i) {
            sp = vec[i].first, ep = vec[i].second;
            if(mark[vec[i].first]) continue;
            for(int j = sp; j <= ep; ++j) {
                mark[j] = true;
            }
        }
        size = s.length();
        for(int i = 0; i < size; ++i) {
            if(!mark[i]) {
                ans = max(ans, cnt);
                cnt = 0;
            } else {
                cnt++;
            }
        }
        ans = max(ans, cnt);
        return ans;
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值