【leetcode】32. Longest Valid Parentheses

最长的有效括号对。

遇到非法括号对应该重新计算

这题不能使用递归来写,因为有一个输入长度是17173,会爆栈。因此得手动模拟栈调用。

 

public class Solution {
    private static class StackFrame {
        public final char left;
        private int num;
        public StackFrame(char left) {
            this.left = left;
        }
        @Override
        public String toString() {
            return "StackFrame [left=" + left + ", num=" + num + "]";
        }
    }
    
    private static final Stack<StackFrame> stack = new Stack<StackFrame>();
    
    public int longestValidParentheses(String s) {
        stack.clear();
        stack.push(new StackFrame('#'));
        int maxNum = 0;
        
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (isLeft(c)) {
                stack.push(new StackFrame(c));
            } else if (isPair(stack.peek().left, c)) {
                StackFrame frame = stack.pop();
                stack.peek().num += frame.num + 2;
                if (stack.peek().num > maxNum) {
                    maxNum = stack.peek().num;
                }
            } else {
                stack.peek().num = 0;
                if (stack.size() > 1) {
                    while (stack.size() > 1) {
                        stack.pop();
                    }
                }
            } 
        }
        return maxNum;
    }
    
    private boolean isLeft(char c) {
        return c == '(' || c == '[' || c == '{';
    }
    
    private boolean isPair(char left, char right) {
        if (left == '(') {
            return right == ')';
        } else if (left == '[') {
            return right == ']';
        } else {
            return right == '}';
        }
    }
}

 

posted @ 2016-04-09 23:34  -六月飞雪-  阅读(203)  评论(0编辑  收藏  举报