Longest Valid Parentheses

描述
Given a string containing just the characters ’(’ and ’)’, find the length of the longest valid (wellformed)
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、如果栈为空,栈中无可与此右括号配对的左括号(有也是之前判断过的);同时记录右括号的位置:有效起始点。

    2、否则,栈顶元素(左括号)出栈,与当前右括号配对。

      1)出栈后,栈为空的话,有效序列长度为当前右括号位置与左括号的位置距离。

      2)否则,栈中还有左括号,有效长度为栈中括号位置的下一位置到右括号的距离。

public int longestValidParentheses(String s) {
        Stack<Integer> left = new Stack<Integer>();
        int _max = 0, last = -1;

        for(int i = 0;  i < s.length(); ++i){
            if(s.charAt(i) == '(') {
                left.add(i);
            }
            else {
                if(left.empty()) {
                    last = i;
                }
                else {
                    left.pop();
                    if(left.empty()){
                        _max = Math.max(_max, i - last);
                    }else{
                        _max = Math.max(_max, i - left.peek());
                    }
                }
            }
        }
        return _max;
    }

 

posted @ 2016-05-16 14:24  no_one  阅读(86)  评论(0编辑  收藏  举报