LeetCode


题目:

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.

思路:

在栈中保存上一个"("的位置

package ds;

import java.util.Stack;

public class LongestValidParentheses {

public int longestValidParentheses(String s) {
int len;
if (s == null || (len = s.length()) < 2) return 0;
Stack
<Integer> stack = new Stack<Integer>();
int max = 0;
int lastIndex = -1;
int i = 0;
while (i < len) {
if (s.charAt(i) == '(') {
stack.push(i);
}
else {
if (stack.isEmpty()) {
lastIndex
= i;
}
else {
stack.pop();
if (stack.isEmpty()) {
max
= Math.max(max, i - lastIndex);
}
else {
max
= Math.max(max, i - stack.peek());
}
}
}
++i;
}

return max;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
LongestValidParentheses l = new LongestValidParentheses();
System.out.println(l.longestValidParentheses(
""));
}

}

 

本站声明
本文转载自:http://www.cnblogs.com/shuaiwhu/p/5066977.html     作者:Longest Valid Parentheses - NULL00     发布日期:2015/12/22     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号