【LeetCode】55. Longest Valid Parentheses

题目描述(Hard)

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

题目链接

https://leetcode.com/problems/longest-valid-parentheses/description/

Example 1:

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

Example 2:

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

算法分析

遇见左括号则将序号入栈,遇见右括号则出栈;同时保存上一个落单的')'位置,出栈时记录最大长度。

提交代码:

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

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82558480