美文网首页
LeetCode每日一题:longest valid paren

LeetCode每日一题:longest valid paren

作者: yoshino | 来源:发表于2017-06-30 09:38 被阅读27次

问题描述

Given a string containing just the characters'('and')', find the length of the longest valid (well-formed) parentheses substring.
For"(()", the longest valid parentheses substring is"()", which has length = 2.
Another example is")()())", where the longest valid parentheses substring is"()()", which has length = 4.

问题分析

一般来说括号匹配都是用栈来实现的,只需要记录合法序列的开头和结尾即可。

代码实现

public int longestValidParentheses(String s) {
        if (s.length() == 0) return 0;
        int len = 0, last = -1;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') stack.push(i);
            else {
                if (stack.isEmpty()) last = i;
                else {
                    stack.pop();
                    if (stack.isEmpty()) len = Math.max(len, i - last);
                    else len = Math.max(len, i - stack.peek());
                }
            }
        }
        return len;
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:longest valid paren

      本文链接:https://www.haomeiwen.com/subject/zvjbcxtx.html