Created
November 13, 2016 07:20
-
-
Save pungrue26/88e9de5ace76ed5b062feb6eaa9dc390 to your computer and use it in GitHub Desktop.
LeetCode, Longest Valid Parentheses
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.isEmpty()) { | |
return 0; | |
} | |
Stack<Pair> stack = new Stack<>(); | |
final int n = s.length(); | |
boolean [] b = new boolean [n]; | |
for (int i = 0; i < n; i++) { | |
if (s.charAt(i) == ')' && !stack.isEmpty() && stack.peek().c == '(') { | |
b[stack.pop().index] = b[i] = true; | |
} else { | |
stack.push(new Pair(i, s.charAt(i))); | |
} | |
} | |
// System.out.println(Arrays.toString(b)); | |
int maxLen = 0, len = 0; | |
for (int i = 0; i < n; i++) { | |
if (b[i]) { | |
len++; | |
} else { | |
maxLen = Math.max(maxLen, len); | |
len = 0; | |
} | |
} | |
maxLen = Math.max(maxLen, len); | |
return maxLen; | |
} | |
class Pair { | |
int index; | |
char c; | |
Pair (int i, char ch) { | |
index = i; | |
c = ch; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment