[Leetcode] 32. Longest Valid Parentheses

来源:互联网 发布:sql insert into 条件 编辑:程序博客网 时间:2024/05/12 07:42

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.

import java.util.Stack;public class Solution {    public int longestValidParentheses(String s) {        if(s == null || s.length() <= 1) return 0;        Stack<Integer> stack = new Stack<Integer>();        int max = 0;        int start = 0;        for(int i = 0; i < s.length(); i++){            char c = s.charAt(i);            if(c == '('){                stack.push(i);            } else {                if(stack.isEmpty()){                    start = i + 1;                } else {                    stack.pop();                    if(stack.isEmpty()){                        max = Math.max(max, i - start + 1);                    } else {                        max = Math.max(max, i - stack.peek());                    }                }            }        }        return max;    }}


0 0