• Leetcode32. 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.

    solution:用stack,复杂度O(n)

    package leetcode2;
    
    import java.util.Stack;
    
    public class LongestValid_Parentheses {
        public static int longest_VP_DP(String s) {
            Stack<Integer> re =new Stack<Integer>();
            int start=-1;
            int maxl=0;
            int location;
            for(int i=0;i<s.length();i++){
                if (s.charAt(i)=='('){
                    re.push(i);
                }else{
                    if(re.empty()){
                        start=i;
                    }else{
                    location=re.pop();
                    if(re.empty()){
                        maxl=Math.max(maxl, i-start); //外围没有(括号了,到i已得到一个局部最大值
                    }else{
                        maxl=Math.max(maxl, re.peek()-i);  //外围还有(,没有结束哦
                    }
                    }
                }
                
            }
            return maxl;
            
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
        String string="()()(";
        System.out.println(longest_VP_DP(string));
        }
    
    }
  • 相关阅读:
    数据查询
    泰勒展开及其应用
    搜索排序算法
    因子分解机 FM
    偏差方差分解
    Softmax 损失-梯度计算
    目标检测网络之 Mask R-CNN
    目标检测网络之 R-FCN
    深度学习-conv卷积
    目标检测网络之 YOLOv3
  • 原文地址:https://www.cnblogs.com/joannacode/p/4389328.html
Copyright © 2020-2023  润新知