首页 > 其他 > 详细

【leetcode】32. Longest Valid Parentheses

时间:2016-04-10 01:01:34      阅读:308      评论:0      收藏:0      [点我收藏+]

这题不能使用递归来写,因为有一个输入长度是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 == ‘}‘;
        }
    }
}

 

【leetcode】32. Longest Valid Parentheses

原文:http://www.cnblogs.com/lanhj/p/5373071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!