您的位置:首页 > 其它

leetcode 32. Longest Valid Parentheses——(use stack)

2016-06-07 09:47 369 查看
import java.util.Stack;

//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.

public class Solution {

public static void main(String[] args) {
String input = "(())()";
int output = longestValidParentheses(input);
System.out.println(output);
}

public static int longestValidParentheses(String s) {
if(s.length() == 0){
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int lengthBefore = 0;														//为括号之前有多少已经匹配成功的括号串
int max = 0;
if(s.charAt(0) == '('){
stack.push(lengthBefore);
}
for(int i = 1;i<s.length();i++){
if(s.charAt(i) == '('){
stack.push(lengthBefore);											//将'('前已经成功匹配的有效括号串push入栈中
lengthBefore = 0;
}else{
if(stack.isEmpty()){
lengthBefore = 0;
}else{
lengthBefore = lengthBefore+stack.pop()+2;						//')'成功匹配后,有效括号串的长度为:2+匹配成功的'('之前的有效括号串长度+本反括号')'之前的有效括号串长度
}
max = Math.max(max, lengthBefore);
}
}
return max;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: