• 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
  • 相关阅读:
    如何安装vue-cli脚手架环境
    使用vw,vh对页面进行布局
    ParseChat聊天室应用项目源码
    不错的找茬游戏源码项目
    山寨山寨版手机安全卫士项目
    高仿精仿金山手机卫士源码项目完整版
    java斗地主游戏项目源码
    ios版塔防类游戏源码
    ios媒体视频播放器应用项目
    仿iphone动态萤火虫锁屏应用源码
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4493853.html
Copyright © 2020-2023  润新知