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


    描述
    Given a string containing just the characters ’(’ and ’)’, find the length of the longest valid (wellformed) 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.
    分析
    这道题是求最长的括号序列,比较容易想到用栈这个数据结构。基本思路就是维护一个栈,遇到左括号就进栈,遇到右括号则出栈,并且判断当前合法序列是否为最 长序列。不过这道题看似思路简单,但是有许多比较刁钻的测试集。具体来说,主要问题就是遇到右括号时如何判断当前的合法序列的长度。比较健壮的方式如下:
    (1) 如果当前栈为空,则说明加上当前右括号没有合法序列(有也是之前判断过的);
    (2) 否则弹出栈顶元素,如果弹出后栈为空,则说明当前括号匹配,我们会维护一个合法开始的起点start,合法序列的长度即为当前元素的位置 -start+1;否则如果栈内仍有元素,则当前合法序列的长度为当前栈顶元素的位置下一位到当前元素的距离,因为栈顶元素后面的括号对肯定是合法的,而 且左括号出过栈了。
    因为只需要一遍扫描,算法的时间复杂度是O(n),空间复杂度是栈的空间,最坏情况是都是左括号,所以是O(n)。
    代码

     1 package StacksAndqueues;
     2 
     3 import java.util.Stack;
     4 
     5 public class LongestValidParentheses {
     6 
     7     public static void main(String[] args) {
     8         // TODO Auto-generated method stub
     9 //        String s="(())())";
    10         String s=")()())";
    11         System.out.println(longestValidParentheses(s));
    12     }
    13 
    14     public static int longestValidParentheses(String s) {
    15         int max_len = 0, last = -1; // the position of the last ')'
    16         Stack<Integer> lefts = new Stack<Integer>(); // keep track of the positions of non-matching '('s
    17         for (int i = 0; i < s.length(); ++i) {
    18             if (s.charAt(i) == '(') {
    19                 lefts.push(i);
    20             } else {
    21                 if (lefts.empty()) {
    22                     // no matching left
    23                     last = i;
    24                 } else {
    25                     // find a matching pair
    26                     lefts.pop();
    27                     if (lefts.empty()) {
    28                         max_len = Math.max(max_len, i - last);
    29                     } else {
    30                         max_len = Math.max(max_len, i - lefts.peek());
    31                     }
    32 
    33                 }
    34             }
    35         }
    36         return max_len;
    37     }
    38 
    39 }
  • 相关阅读:
    Unity性能优化-遮挡剔除
    unity AssetBundle
    unity中Animation与Animator的区别
    VS 项目没有“添加引用”选项
    VS 右键属性闪一下啥也打不开问题
    协程
    协程
    Python 线程和进程(2)
    线程锁
    ssh传文件加MD5
  • 原文地址:https://www.cnblogs.com/ncznx/p/9270233.html
Copyright © 2011-2022 走看看