Thursday, June 12, 2014

LeetCode LongestValideParentheses

Similar idea with valid parentheses. Using a stack to store the left perenthese.


public int longestValidParentheses(String s) {
        int maxLen = 0;
int lastIndex = -1;
Stack<Integer> lefts = new Stack<Integer>();
for (int i=0; i<s.length();i++) {
if (s.charAt(i) == '(') {
lefts.push(i);
} else {
if (lefts.empty()) {
lastIndex = i;
} else {
lefts.pop();
if (lefts.empty()) {
                                             
maxLen = Math.max(maxLen, i-lastIndex);
} else {
                                                //Count the current length
maxLen = Math.max(maxLen, i - lefts.peek());
}
}
}
}
return maxLen;
    }

No comments:

Post a Comment