Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created March 2, 2015 04:34
Show Gist options
  • Save dmnugent80/6655ea3dbac44eb11f39 to your computer and use it in GitHub Desktop.
Save dmnugent80/6655ea3dbac44eb11f39 to your computer and use it in GitHub Desktop.
Max Valid Parentheses
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stk = new Stack<Integer>();
int left = -1;
int maxCount = 0;
for (int i = 0; i < s.length(); i++){
if (s.charAt(i) == '('){
stk.push(i);
}
else{
if (stk.empty()){
left = i;
}
else{
stk.pop();
if (stk.empty()){
maxCount = Math.max(maxCount, i-left);
}
else{
maxCount = Math.max(maxCount, i - stk.peek());
}
}
}
}
return maxCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment