Created
April 20, 2015 18:49
-
-
Save phamd1989/818faaff3e1a47966de6 to your computer and use it in GitHub Desktop.
Interesting solution to the problem of finding the Longest Valid Parentheses substring
This file contains 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) { | |
int maxLen = 0; | |
// the index that right before the beginning of the current longest substring | |
int left = -1; | |
Stack<Integer> stack = new Stack<Integer>(); | |
for (int i=0; i<s.length(); i++) { | |
if (s.charAt(i) == '(') { | |
stack.push(i); | |
} else { | |
if (stack.isEmpty()) { | |
// more ')' than '(', consider a new substring | |
left = i; | |
} else { | |
stack.pop(); | |
if (stack.isEmpty()) { | |
// stack is empty, consider adding the pair to the current substring | |
maxLen = Math.max(maxLen, i - left); | |
} else { | |
// stack is not empty, more '(' than ')' | |
// get the difference between the current pos and the first '(' on stack | |
maxLen = Math.max(maxLen, i - stack.peek()); | |
} | |
} | |
} | |
} | |
return maxLen; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment