Longest Valid Parentheses

来源:互联网 发布:淘宝上的电视机能买吗 编辑:程序博客网 时间:2024/06/08 18:24

原题:

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.

即找出给定字符串的满足括号匹配的子串的长度。


思考过程:

一开始觉得很难入手,总不能遍历所有子串。后来想到,阻挡两个符合题意的子串的,不是‘(’就是‘)’,所以找到这种阻挡两个子串的元素作为子串端点,再给相邻值做差,找到最大的差就是最长的子串(一开始要添加-1和s.length()作为端点)。多余的‘)’很好找,栈里没有元素时候,栈外来了‘)’,就是多余的。但多余的‘(’不好找。一开始我想的是先把‘)’找出来,遍历完整个字符串,栈里的‘(’就是多余的。但这样不好比较它们的index,毕竟相邻值做差要用到排序,于是我把它们存到priority里,再一次次取出来做差,找到最长子串长度。代码如下:

public int longestValidParentheses1(String s) {    int res = 0;    Stack<Integer> stack = new Stack<>();    PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();    priorityQueue.offer(-1);    priorityQueue.offer(s.length());//必须加上两个端点。    for (int i = 0;i < s.length();i++){        if (s.charAt(i) == '(') stack.push(i);        if (s.charAt(i) == ')') {            if (stack.isEmpty()) priorityQueue.offer(i);            else {                stack.pop();            }        }    }    while (!stack.isEmpty()) priorityQueue.offer(stack.pop());    while (priorityQueue.size() > 1){        int i = priorityQueue.poll();        res = Math.max(res,priorityQueue.peek() - i - 1);    }    return res;
}
结果超时了。因为排序要增加log n 倍时间复杂度。
后来看了官方代码,大受启发。
解题思路:
也是找到分隔子串的多余的'(',')'作为端点,当然还得加上-1这个起始端点。然后遇到')'就出栈,而多余的')'会和-1抵消,使得栈为空,此时再把这个')'放进去就好了,它是更新的端点。如果不是多余的')',就计算i-端点,和当前子串最长长度比较,如果比它小,最长子串长度更新为这个数,以此类推。
原创粉丝点击