Longest Valid Parentheses 最长的合法括号序列

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.

做法是从左到右扫描数组,碰到 '(' ,当前的index入栈;

碰到 ')' ,如果当前栈顶不为空且index对应的值为')'出栈,反之当前的index入栈。

最后,如果栈为空,表示全都匹配,长度为string的长度。

如果不为空,留在栈中的都是那些不能匹配的括号的index,相邻index间隔的长度记为中间合法的括号的长度。

取其中的最大长度即为最大合法括号序列的长度。

时间复杂度O ( n )

空间复杂度O ( n )

运行时间:


代码:

public class LongestValidParentheses {
    public int longestValidParentheses(String s) {
        Stack<Integer> store = new Stack<>();//store the index of character
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                store.push(i);
            } else {
                if (!store.empty() && s.charAt(store.peek()) == '(') {
                    store.pop();
                } else {
                    store.push(i);
                }
            }
        }
        if (store.empty()) {
            return s.length();
        }
        int max = 0;
        int right = s.length(), left = 0;// adjacent indices should be valid parentheses.
        while (!store.empty()) {
            left = store.pop();
            max = Math.max(max, right - left - 1);
            right = left;
        }
        max = Math.max(max, right);// do not forget the first
        return max;
    }
}
参考资料:

https://leetcode.com/discuss/7609/my-o-n-solution-using-a-stack

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值