Longest Valid Parentheses
Mar 1 '12
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.
public class Solution {
public int longestValidParentheses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
//()(()
int sz = s.length();
Stack<Integer> stack = new Stack<Integer>();
int max = 0;
for(int i=0; i<sz; i++) {
char c = s.charAt(i);
if(c=='(') {
stack.push(i);
} else {
if(!stack.isEmpty() && s.charAt(stack.peek()) == '(' ){
stack.pop();
if(stack.isEmpty() ) {
max = Math.max(max, i+1);
} else {
int x = i-stack.peek();
max = Math.max(max, x);
}
} else {
stack.push(i);
}
}
}
return max;
}
}