zoukankan      html  css  js  c++  java
  • 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.

    参考:http://www.cnblogs.com/easonliu/p/3637429.html

    C++ 代码实现:

    #include<iostream>
    #include<string>
    #include<stack>
    using namespace std;
    
    class Solution
    {
    public:
        int longestValidParentheses(string s)
        {
            stack<int> st;
            if(s.empty())
                return 0;
            bool a[s.length()];
            size_t i;
            for(i=0; i<s.length(); i++)
            {
                if(s[i]=='(')
                {
                    //还没有匹配的都设置为false
                    a[i]=false;
                    st.push(i);
                }
                else if(!st.empty()&&s[i]==')')
                {
                    //每次匹配设置两个为true
                    a[i]=true;
                    a[st.top()]=true;
                    st.pop();
                }
                else
                    a[i]=false;
            }
            int max=0;
            int count=0;
            for(i=0; i<s.length(); i++)
            {
                if(a[i])
                    count++;
                else
                    count=0;
                if(count>max)
                    max=count;
            }
            return max;
        }
    };
    
    int main()
    {
        Solution s;
        string str="(()";
        cout<<s.longestValidParentheses(str)<<endl;
    }
  • 相关阅读:
    BZOJ 3529 数表
    BZOJ 3832 Rally
    BZOJ 1086 王室联邦
    BZOJ 2738 矩阵乘法
    2656565
    小L的区间求和
    小L的直线
    Co-prime 杭电4135
    POJ 跳蚤
    B
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4119766.html
Copyright © 2011-2022 走看看