Skip to content

Instantly share code, notes, and snippets.

@pungrue26
Created November 13, 2016 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pungrue26/88e9de5ace76ed5b062feb6eaa9dc390 to your computer and use it in GitHub Desktop.
Save pungrue26/88e9de5ace76ed5b062feb6eaa9dc390 to your computer and use it in GitHub Desktop.
LeetCode, Longest Valid Parentheses
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