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;
    }
  • 相关阅读:
    关键词提取算法TextRank
    我的博文目录整理
    Windows Azure一些小技巧集合
    js数组和树互转
    this.props.form.validateFields回调不执行问题
    d3的4.x与3.x版本的区别
    d3提示框,虚线,选择区域
    d3布局
    d3文件导入和导出
    d3交互
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4119766.html
Copyright © 2011-2022 走看看