LeetCode- Longest Valid Parentheses(JAVA)

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 “()()”

class Solution {
    public int longestValidParentheses(String s) {
        int l = s.length();
        if(l < 2) {
            return 0;
        }
        
        int[] dp = new int[l + 1];
        // if s[i - 1] == ")",left = i - 2 - dp[i -1]
        // if s[left - 1] =  "(" dp[i] = dp[i - 1] + 2;
        // if left >0 dp[i] =dp[i] + dp[left -1];
        int max = 0;
        
        for(int i = 1; i <= l ;i++ ) {
            if(s.charAt(i - 1) == ')') {
                int left = i - dp[i - 1] - 1;
                if(left < 1) {
                    continue;
                }
                if(s.charAt(left - 1) != '(') {
                    continue;
                }
                
                dp[i] = dp[i - 1] + 2;
                dp[i] = dp[i] + dp[left - 1];
                max = Math.max(max, dp[i]);
            }
        }
        return max;
        
    }
}
發佈了51 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章