Longest Valid Parentheses_Leetcode_#32

来源:互联网 发布:python是什么语言 编辑:程序博客网 时间:2024/06/07 04:43

1 题目
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.

2 解法

public class Solution {    public int longestValidParentheses(String s) {        int size = s.length();        Stack<Integer> stack = new Stack<Integer>();        stack.push(-1);        int result = 0;        for(int i = 0; i < size; i++){            if(s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '('){                stack.pop();                result = Math.max(result, i - stack.peek());            }else{                stack.push(i);            }        }        return result;    }}
0 0
原创粉丝点击