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

    The workflow of the solution is as below.

      1. Scan the string from beginning to end.
      2. If current character is '(',
        push its index to the stack. If current character is ')' and the
        character at the index of the top of stack is '(', we just find a
        matching pair so pop from the stack. Otherwise, we push the index of
        ')' to the stack.
      3. After the scan is done, the stack will only
        contain the indices of characters which cannot be matched. Then
        let's use the opposite side - substring between adjacent indices
        should be valid parentheses.
      4. If the stack is empty, the whole input
        string is valid. Otherwise, we can scan the stack to get longest
        valid substring as described in step 3.
    class Solution {
    public:
        int longestValidParentheses(string s) {
            int n = s.length(), longest = 0;
            stack<int> st;
            for (int i = 0; i < n; i++) {
                if (s[i] == '(') st.push(i);
                else {
                    if (!st.empty()) {
                        if (s[st.top()] == '(') st.pop();
                        else st.push(i);
                    }
                    else st.push(i);
                }
            }
            if (st.empty()) longest = n;
            else {
                int a = n, b = 0;
                while (!st.empty()) {
                    b = st.top(); st.pop();
                    longest = max(longest, a-b-1);
                    a = b;
                }
                longest = max(longest, a);
            }
            return longest;
        }
    };
    

      

  • 相关阅读:
    SQL Server 创建触发器(trigger)
    jQuery插件-json2.js
    Opengl创建机器人手臂代码示例
    OpenGL超级宝典完整源码(第五版)
    基于Opengl的太阳系动画实现
    Opengl创建几何实体——四棱锥和立方体
    ubuntu16.04安装labelme
    Visual Studio Command Prompt 工具配置方法
    OpenNi安装示例
    Opencv读取图片像素值并保存为txt文件
  • 原文地址:https://www.cnblogs.com/apanda009/p/7807563.html
Copyright © 2011-2022 走看看