zoukankan      html  css  js  c++  java
  • 【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 == '}';
            }
        }
    }
  • 相关阅读:
    Enable Zombie
    python中调用c文件中的函数(ubuntu)
    NSNotificationCenter使用心得(原)
    TCP/UDP
    xcconfig 文件使用( 转 )
    TS流解析 (转)
    c 数字和char类型转换
    结构体如何使用NSData包装
    NSValue 保存定长的结构体
    遍历DOM的所有节点,输出宽度高度都大于50的元素节点名称
  • 原文地址:https://www.cnblogs.com/lanhj/p/5373071.html
Copyright © 2011-2022 走看看