zoukankan      html  css  js  c++  java
  • leetcode32. Longest Valid Parentheses

    题目描述:

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    Example 1:

    Input: "(()"
    Output: 2
    Explanation: The longest valid parentheses substring is "()"
    

    Example 2:

    Input: ")()())"
    Output: 4
    Explanation: The longest valid parentheses substring is "()()"

    解题思路:

    一说到括号匹配,我首先就会想到栈,但是智障如我一开始居然想往里存括号,显然存括号是没有什么用的,儿下标有更多的信息

    所以我们存左括号的下标。

    每当遇到有括号时,检查栈是否为空,如果不为空,说明有可以与之匹配的左括号。

    若为空我们需要一个int值来记录的新的起始点。

    代码:

    class Solution {
    public:
        int longestValidParentheses(string s) {
            stack<int> stk;
            int m = 0;
            int start = 0;
            for(int i = 0; i < s.size(); i++){
                if(s[i] == '('){
                    stk.push(i);
                }else{
                    if(stk.empty()){
                        start = i + 1;
                    }else{
                        stk.pop();
                        m = stk.empty() ? max(m, i - start + 1) : max(m, i - stk.top());
                    }
                }
            }
            return m;
        }
    };

    据说还有动态规划解法?

    反正我现在不想看:)

  • 相关阅读:
    [Codechef Coders' Legacy 2018 CLSUMG]Sum of Primes
    [HDU4630]No Pain No Game
    [Luogu4329][COCI2006]Bond
    [数论]Gcd/ExGcd欧几里得学习笔记
    [数论]线性基学习笔记
    [Luogu5190][COCI2010]PROGRAM
    IIS7 HTTPS 绑定主机头,嘿嘿,转
    React
    ios
    iOS10 权限配置
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9120395.html
Copyright © 2011-2022 走看看