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.
Idea: Use a stack to validate the parentheses. Use a pointer i to scan the string from left to right,
- when a '(' is visited: push i to the stack;
- when a ')' is visited and the top of the stack is '(': first pop the top of the stack, then calculate the length of the parentheses following these rules:
1) if the stack is empty, then from 0 to i is a valid parentheses, the length is i+1;
2) if the stack is not empty, then from the current top of the stack to the current i is a valid parentheses, the length is i-stack.peek().
- when a ')' is visited, but the top of the stack is not '(': this means the former parentheses in the stack is not valid. push i to the stack to terminate the former parentheses cached, in other words, to make the position of ')' as a new start point for following validations.
Time: O(n) Space: O(1)
Code:
public class Solution {
public int longestValidParentheses(String s) {
if(s.length()<=1)
return 0;
Stack<Integer> stack=new Stack<Integer>();
int result=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='(')
stack.push(i);
else
{
if(!stack.isEmpty()&&s.charAt(stack.peek())=='(')
{
stack.pop();
int curLength=(stack.isEmpty())?i+1:i-stack.peek();
result=Math.max(result,curLength);
}
else
stack.push(i);
}
}
return result;
}
}
No comments:
Post a Comment