LeetCode - 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.

 

public int longestValidParentheses(String s) {
    int n = s.length();
    Stack<Integer> stack = new Stack<>();
    int len = 0;
    for(int i=0; i<n; i++) {
        char c = s.charAt(i);
        if(c == ')' && !stack.isEmpty() && s.charAt(stack.peek()) == '(') {
            stack.pop();
            if(stack.isEmpty()) {
                len = i+1;
            } else {
                len = Math.max(len, i-stack.peek());
            }
        } else {
            stack.push(i);
        }
    }
    return len;
}

 

int longestValidParentheses(string s) {
    int res = 0;
    stack<int> st;
    for(int i=0; i<s.size(); i++) {
        if(!st.empty() && s[i]-s[st.top()] == 1) {
            st.pop();
            int start = st.empty() ? -1 : st.top();
            res = max(res, i-start);
        } else {
            st.push(i);
        }
    }
    return res;
}

 

 

你可能感兴趣的:(LeetCode)