码迷,mamicode.com
首页 > 其他好文 > 详细

32. Longest Valid Parentheses

时间:2018-10-11 01:35:51      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:lin   ret   time   tac   form   length   The   ack   ati   

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 "()()"

AC code:

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;
    }
};
Runtime: 8 ms, faster than 62.98% of C++ online submissions for Longest Valid Parentheses.

 

 

32. Longest Valid Parentheses

标签:lin   ret   time   tac   form   length   The   ack   ati   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9769908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!