LeetCode 题解(111): Longest Valid Parentheses

题目:

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

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

题解:

首先想到的是动态规划,但是这道题的递推公式不太好理解。而用一个stack比较好理解。

C++版:

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size(), maxLen = 0;
        vector<int> dp(n+1,0);
        for(int i=1; i<=n; i++) {
            int j = i-2-dp[i-1];
            if(s[i-1]=='(' || j<0 || s[j]==')') 
                dp[i] = 0;
            else {
                dp[i] = dp[i-1]+2+dp[j];
                maxLen = max(maxLen, dp[i]);
            }
        }
        return maxLen;
    }
};

Java版:

public class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> left = new Stack<>();
        int overall = 0;
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '(') {
                left.push(i);
            } else {
                if(!left.empty() && s.charAt(left.peek()) == '(') {
                    left.pop();
                    overall = Math.max(overall, (left.empty() ? i + 1 : i - left.peek()));
                } else {
                    left.push(i);
                }
            }
        }
        return overall;
    }
}

Python版:

class Solution:
    # @param {string} s
    # @return {integer}
    def longestValidParentheses(self, s):
        overall = 0
        l = []
        for i in range(len(s)):
            if s[i] == '(':
                l.append(i)
            else:
                if len(l) != 0 and s[l[-1]] == '(':
                    l = l[:-1]
                    if len(l) == 0:
                        overall = max(overall, i + 1)
                    else:
                        overall = max(overall, i - l[-1])
                else:
                    l.append(i)
        return overall


你可能感兴趣的:(Algorithm,LeetCode,面试题)