Created
December 19, 2017 23:26
-
-
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
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) { | |
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