String://给定字符串,字符串中只含有"(&qu

2016-06-08  本文已影响14人  敲一手烂代码
public static int longestValidParentheses(String s) {
        char[] ary = s.toCharArray();
        int max = 0;
        int flag = -1;
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < ary.length; i++) {
            if (ary[i]=='(') {
                stack.push(i);
            } else {
                if (stack.isEmpty()) {
                    flag = i;
                } else {
                    stack.pop();
                    if (stack.isEmpty()) {
                        max = Math.max(max, i-flag);
                    } else {
                        max = Math.max(max, i-stack.peek());
                    }
                }
            }
        }
        return max;
    }
上一篇下一篇

猜你喜欢

热点阅读