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.

The idea is the stack top is the left boundry of the current longest possible valid parentheses

public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
}
else { // if char is ")"
if (!stack.isEmpty() && s.charAt(stack.peek()) == '(') {
stack.pop();
maxLen = Math.max(maxLen, stack.isEmpty()? i + 1: i - stack.peek());
}
else {
stack.push(i);
}
}
}
return maxLen;
}
}

### Like this:

Like Loading...

*Related*