[LeetCode] 32. Longest Valid Parentheses

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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章