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

来源:互联网 发布:北京棉花检验数据平台 编辑:程序博客网 时间:2024/05/22 08:14

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
原创粉丝点击