Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 19, 2017 23:26
Show Gist options
  • Save jianminchen/0cc3fcf1df04a2a09b548d4da6d8a59c to your computer and use it in GitHub Desktop.
Save jianminchen/0cc3fcf1df04a2a09b548d4da6d8a59c to your computer and use it in GitHub Desktop.
Leetcode 32 - study Java code of Leetcode 32 - longest valid parentheses - Hard level algorithm - code is from blog: http://blog.csdn.net/worldwindjp/article/details/39460161
public class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() == 0) {
return 0;
}
int start = -1;
int maxLength = 0;
Stack stack = new Stack();
for(int i = 0;i < s.length(); i++) {
if(s.charAt(i) == '(') {
stack.push(i);
} else {
if(!stack.empty()) {
stack.pop();
if(stack.empty() == true) {
maxLength = Math.max(i - start , maxLength);
} else {
maxLength = Math.max(i - (int)stack.peek() , maxLength);
}
} else {
start = i;
}
}
}
return maxLength;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment