LeetCode[32] Longest Valid Parentheses!

Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

For “(()”, the longest valid parentheses substring is “()”, which has length = 2.

Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.

分析:

还是使用栈。不过因为要求的是长度,所以这次入栈的是字符的下标。需要注意的是,”()((()))”的length = 8。

代码:

public class Solution {
public int longestValidParentheses(String s) {
int maxLen = 0;
int left = -1;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '('){
stack.push(i);
} else {
if (stack.isEmpty()) {
left = i;
} else {
stack.pop();
if (stack.isEmpty()) {
maxLen = Math.max(maxLen, i - left);
} else {
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
}
return maxLen;
}
}

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :