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 "()" are, which has length = 2.
Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.
Problem Solving Ideas:
A lot of methods, is the Java for Leetcode 020 Valid parentheses The continuation of the topic, so we continue to use the stack of ideas to solve this problem, which requires an index to maintain the last ') ' where it appears. The Java code is as follows:
static public int longestvalidparentheses (String s) {int maxLength = 0,index=-1; stack<integer> stack = new stack<integer> (); for (int i = 0; i < s.length (); i++) {if (S.charat (i) = = ' (') St Ack.push (i); else {if (Stack.empty ()) Index=i;else{stack.pop (); if (Stack.isempty ()) MaxLength = Math.max (MaxLength, I- index); else Maxlength=math.max (MaxLength, I-stack.peek ());}}} return maxLength;}
Java for Leetcode 032 longest Valid parentheses