【LeetCode】32. Longest Valid Parentheses

Difficulty: Hard

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/longest-valid-parentheses/

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实现

 

posted @ 2019-09-28 22:26  华仔要长胖  阅读(178)  评论(0编辑  收藏  举报