Title:
Given A string containing just the characters ‘(‘ ‘)‘ and, find the length of the longest valid (well-formed) parenthe SES substring.
for " (() ", the longest valid parentheses substring is " () ", which has length = 2.
Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.
Test Instructions:
given a string value containing the character " ('  AND  ", Find the longest valid brace substring.
< Span style= "Background-color:rgb (255,255,255)" for &NBSP; " (() " , the longest valid substring is " () ", length 2.
< Span style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; line-height:30px ">< Span style= "Background-color:rgb (255,255,255)" and another example is " () ()) ", where the longest valid brace substring is " () () ", length 4.
Algorithm Analysis:
- The stack is always "index of poor brackets that are not well-fitted"
- Is ' (' when the push
- Is ') ', the explanation may be paired; see if Stack top is an opening parenthesis, or not, push the current closing parenthesis
- Yes, pop that paired left parenthesis, and then update res:i and top (the last mismatched) index minus, which is the current longest of the section I belongs to. If a pop on the entire stack empty, the front is fully equipped with the right, that Res is the largest =i+1
AC Code:
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; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Longest Valid parentheses