[LeetCode] 32. Longest Valid Parentheses

更新于 2018-09-24  约 4 分钟

Problem

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 "()()"

Solution

DP

class Solution {
    public int longestValidParentheses(String s) {
        //()((()))
        //()()()()
        int max = 0, left = 0;
        int[] dp = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') left++;
            else {
                if (left != 0) {
                    dp[i] = dp[i-1]+2;
                    if (i-dp[i] >= 0) dp[i] += dp[i-dp[i]];
                    max = Math.max(max, dp[i]);
                    left--;
                }
            }
        }
        return max;
    }
}

Stack


class Solution {
    public int longestValidParentheses(String s) {
        //stack to store index
        Stack<Integer> stack = new Stack<>();
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ')' && !stack.isEmpty() && s.charAt(stack.peek()) == '(') {
                //remove this pair
                stack.pop();
                
                //update the length of this pair
                //
                //if starts with )
                if (!stack.isEmpty()) max = Math.max(max, i-stack.peek());
                //if starts with (
                else max = i+1;
            } else {
                stack.push(i);
            }
        }
        return max;
    }
}
阅读 987更新于 2018-09-24

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页
目录