zoukankan      html  css  js  c++  java
  • LeetCode Longest Valid Parentheses

    class Solution {
    public:
        int longestValidParentheses(string s) {
            vector<int> stack;
            int maxlen = 0;
            int curlen = 0;
            int last = -1;
            int len = s.length();
            for (int i=0; i<len; i++) {
                char ch = s[i];
                if (ch == '(') {
                    stack.push_back(i);
                    continue;
                }
                if (stack.empty()) {
                    last = i;
                    continue;
                }
                stack.pop_back();
                if (stack.empty()) {
                    curlen = i - last;
                } else {
                    curlen = i - stack.back();
                }
                
                if (curlen > maxlen) maxlen = curlen;
            }
            
            return maxlen;
        }
    };

    参考:http://www.cnblogs.com/zhuli19901106/p/3547419.html

    last用来记录最后一个无法匹配的右括号的位置,当stack为空时,必然存在一个合法的括号序列,而这个序列的起始肯定是last后面的一个位置。

    智商有限,做了好久,只有看答案了。。。

    第二轮:

    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.

    还是没想起来,真是硬伤啊,真是硬伤。。。

    class Solution {
    public:
        int longestValidParentheses(string s) {
            int len = s.size();
            if (len < 2) return 0;
            int last_invalid = -1;
            
            int pos = 0;
            int maxlen = 0;
    
            vector<int> idx;
            while (pos<len) {
                char ch = s[pos];
                
                if (ch == '(') {
                    idx.push_back(pos);
                    pos++;
                    continue;
                }
                
                if (idx.empty()) {
                    last_invalid = pos;
                    pos++;
                    continue;
                }
                
                idx.pop_back();
                if (idx.empty()) {
                    maxlen = max(maxlen, pos - last_invalid);
                } else {
                    maxlen = max(maxlen, pos - idx.back());
                }
                pos++;
            }
            return maxlen;
        }
    };
  • 相关阅读:
    database homework1
    数据库基础
    MySQL操作
    [BZOJ 1305][CQOI2009]dance跳舞(网络流+二分答案)
    [BZOJ 1834][ZJOI2010]network 网络扩容(费用流)
    [BZOJ 3931][CQOI2015]网络吞吐量(SPFA+网络流)
    [BZOJ 3576][Hnoi2014]江南乐(博弈论)
    [BZOJ 1086][SCOI2005]王室联邦(贪心?树分块)
    [BZOJ 4765]普通计算姬(分块+树状数组)
    [BZOJ 4802]欧拉函数(Pollard_rho+Miller_Rabin)
  • 原文地址:https://www.cnblogs.com/lailailai/p/3906652.html
Copyright © 2011-2022 走看看