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;
    }
};

据说还有动态规划解法?

反正我现在不想看:)

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9120395.html