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 == '}';
            }
        }
    }
  • 相关阅读:
    Python 执行主程序
    Python 3.0 写日志时出现乱码
    验证文件下载成功
    selenium 校验文件下载成功
    java中Proxy(代理与动态代理)
    简易计算器
    Python正则
    Python logger 没打出行数
    Python logger /logging
    Python configparser 读取指定节点内容失败
  • 原文地址:https://www.cnblogs.com/lanhj/p/5373071.html
Copyright © 2011-2022 走看看