• 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

  • 相关阅读:
    【Java并发】并发笔记(一)
    【深入Java基础】排序算法(一)
    QDU-GZS and String
    牛客网36-A,B题解
    QDU-GZS与素数大法(素数筛法)
    csdn自动展开+去广告+净化剪切板+免登陆(如有侵权,立即删博)
    QDU第一届程序设计大赛——E到I题解法(非官方题解)
    Codeforces Round #529 -C- Powers Of Two(二进制拆分)
    CodeForces
    分配物资(模拟)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4935002.html
Copyright © 2020-2023  润新知