【LeetCode】32. Longest Valid Parentheses

时间:2019-09-28
本文章向大家介绍【LeetCode】32. Longest Valid Parentheses,主要包括【LeetCode】32. Longest Valid Parentheses使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Difficulty: Hard

 More:【目录】LeetCode Java实现

Description

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

Intuition

Method 1: Dynamic Programming

  1. Define subLen[i] as the length of the longest valid parentheses subString which is end with char at index i (s[i]).

  2. If s[i]=='(', subLen[i]=0

      If s[i]=='('  

     If(s[i-subLen[i]-1)==')', subLen[i]=0 

       If(s[i-subLen[i]-1)=='(', subLen[i]=subLen[i-1]+2+subLen[i-subLen[i-1]-2]

Method 2: Using a stack to store the index of '(', and using 2 pointers to store left index and right index of a subString.

Solution

Method 1

    public int longestValidParentheses(String s) {
        if(s==null || s.length()<=0)
            return 0;
        int[] subLen = new int[s.length()];
        int maxLen=0;
        for(int i=1; i<s.length(); i++){
            if(s.charAt(i)==')'){
                int pre = i-subLen[i-1]-1;
                if(pre>=0 && s.charAt(pre)=='('){
                    subLen[i]=subLen[i-1]+2+(pre>0 ? subLen[pre-1] : 0);
                }
                maxLen=Math.max(maxLen,subLen[i]);
            }
        }
        return maxLen;
    }

  

Method 2

    public int longestValidParentheses(String s) {
        if(s==null || s.length()<=0)
            return 0;
        int maxLen=0;
        int left=-1;
        Stack<Integer> stk = new Stack<Integer>();
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i)=='(')
                stk.push(i);
            else{
                if(stk.isEmpty())
                    left=i;
                else{
                    stk.pop();
                    int len = stk.isEmpty() ? i-left : i-stk.peek();
                    maxLen=Math.max(len,maxLen);
                }
            }
        }
        return maxLen;
    }

  

  

Complexity

Time complexity : O(n)

Space complexity :  O(n)

 

 More:【目录】LeetCode Java实现

原文地址:https://www.cnblogs.com/yongh/p/11605247.html