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

来源:互联网 发布:算法导论公开课 编辑:程序博客网 时间:2024/05/01 01:39
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;    }}

0 0
原创粉丝点击