标签:leetcode java longest valid parent
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.
给定一个字符串值包含字符‘(‘
and ‘)‘,
找出最长有效括号子串。
对于 "(()"
,最长有效子串为"()",长度为2.
另一个例子是")()())",其中的最长有效括号子串为"()()",长度为4.
public class Solution { public int longestValidParentheses(String s) { int res = 0; Stack<Integer> stack = new Stack<Integer>(); char[] arr = s.toCharArray(); for (int i = 0; i < arr.length; i++) { if (arr[i] == ')' && !stack.isEmpty() && arr[stack.peek()] == '(') { stack.pop(); if (stack.isEmpty()) res = i + 1; else res = Math.max(res, i - stack.peek()); } else { stack.push(i); } } return res; } }
版权声明:本文为博主原创文章,转载注明出处
[LeetCode][Java] Longest Valid Parentheses
标签:leetcode java longest valid parent
原文地址:http://blog.csdn.net/evan123mg/article/details/46848699