Created
March 2, 2015 04:34
-
-
Save dmnugent80/6655ea3dbac44eb11f39 to your computer and use it in GitHub Desktop.
Max Valid Parentheses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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