首页 > 其他 > 详细

[LC] 32. Longest Valid Parentheses

时间:2019-11-17 09:55:14      阅读:90      评论:0      收藏:0      [点我收藏+]

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


class Solution {
    public int longestValidParentheses(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        LinkedList<Integer> stack = new LinkedList<>();
        int j = -1, res = 0;
        for (int i = 0; i < s.length(); i++) {
            char cur = s.charAt(i);
            if (cur == ‘(‘) {
                stack.offerFirst(i);
            } else if (cur == ‘)‘ && stack.isEmpty()) {
                j = i;
            } else {
                stack.pollFirst();
                    if (stack.isEmpty()) {
                        res = Math.max(res, i - j);  
                    } else {
                        res = Math.max(res, i - stack.peekFirst());
                    }
            }
        }
        return res;
    }
}

 

[LC] 32. Longest Valid Parentheses

原文:https://www.cnblogs.com/xuanlu/p/11875131.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!