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

    Question

    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 1 -- Stack

    Parenthese类的题目,第一反应是用栈。遇到'('入栈,遇到')'出栈。这题关键在于怎样知道当前的valid parenthese length。

    我们用一个变量start来表示当前的第一个'(' 。

    (  (  (  )  )  )  )  )  (

     start                                                             start

    当栈为空时,进来的第一个左括号的位置为当前的start值。

    出栈操作后:

    1. 如果栈为空,说明从start开始的括号都匹配了。因此长度为 current - start + 1

    2. 如果栈不为空,我们知道弹出栈的一定是都已经匹配了的。因此长度为 current - stack.peek()

    因为只扫描了一遍原数组,所以时间复杂度是O(n),空间复杂度是O(n)

     1 public class Solution {
     2     public int longestValidParentheses(String s) {
     3         if (s == null || s.length() < 1) {
     4             return 0;
     5         }
     6         int length = s.length();
     7         Deque<Integer> stack = new LinkedList<Integer>();
     8         int start = 0;
     9         int result = 0;
    10         for (int i = 0; i < length; i++) {
    11             char current = s.charAt(i);
    12             if (current == '(') {
    13                 stack.push(i);
    14             } else {
    15                 if (stack.isEmpty()) {
    16                     start = i + 1;
    17                 } else {
    18                     stack.pop();
    19                     result = stack.isEmpty() ? Math.max(result, i - start + 1) : Math.max(result, i - stack.peek());
    20                 }
    21             }
    22         }
    23         return result;        
    24     }
    25 }

    Solution 2 -- DP

  • 相关阅读:
    sql server 以10分钟分组 统计人数
    【转】锁(lock)知识及锁应用
    虚拟机中实现Linux与Windows之间的文件传输
    sql server 备份恢复效率
    sql server dba常用概念、操作分析char,varchar,nvarchar,varchar(max)
    数据库事务的四大特性以及事务的隔离级别
    SQLServer DBA 三十问(加强版)
    SQLServerDBA十大必备工具---让生活轻松点
    http头
    High performance web site
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4935002.html
Copyright © 2011-2022 走看看