zoukankan      html  css  js  c++  java
  • Longest Valid Parentheses

    Longest Valid Parentheses

    问题:

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    For "(()", the longest valid parentheses substring is "()", which has length = 2.

    Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

    思路:

      栈的经典应用

    我的代码:

    public class Solution {
        public int longestValidParentheses(String s) {
            if(s==null || s.length()==0)    return 0;
            Stack<Integer> stack = new Stack<Integer>();
            int max = 0;
            
            for(int i=0; i<s.length(); i++)
            {
                if(stack.isEmpty() || s.charAt(stack.peek())==')' || s.charAt(i)=='(') stack.push(i);
                else
                {
                    stack.pop();
                    int index = stack.isEmpty()? -1 : stack.peek();
                    max = Math.max(max,i-index);
                }
            }
            return max;
        }
    }
    View Code

    他人代码:

    public int longestValidParentheses(String s) {
        char[] S = s.toCharArray();
        int[] V = new int[S.length];
        int open = 0;
        int max = 0;
        for (int i=0; i<S.length; i++) {
            if (S[i] == '(') open++;
            if (S[i] == ')' && open > 0) {
                V[i] = 2 + V[i-1] + (i-2-V[i-1] > 0 ? V[i-2-V[i-1]] : 0);
                open--;
            }
            if (V[i] > max) max = V[i];
        }
        return max;
    }
    View Code

    学习之处:

    • 不知道这道题为什么在leetcode上hard的难度,思路很容易想,代码很容易些,也一遍就AC了
    • 想的越多,最后写出来的代码越简洁
    • 看别人的代码才发现,这道题的另外一个解法使用动态规划来解, V[i-1] is its previous consecutive parentheses, i-2-V[i-1] is the position right outside this big "( ... )" part. So check if previous big "(...)" is a valid one. 
    • 改掉不好的习惯 day by day
  • 相关阅读:
    springboot系列六、springboot配置错误页面及全局异常
    一行代码完成 Java的 Excel 读写--easyexcel
    Docker搭建Portainer可视化界面
    使用spring-boot-admin对spring-boot服务进行监控
    SpringBoot集成JWT实现权限认证
    安装Docker
    Java的 Excel 读写--easyexcel
    SpringBoot 配置文件提示功能
    Mysql数据库中获取时间
    javascript-观察者模式
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4493853.html
Copyright © 2011-2022 走看看