[leetcode]32. Longest Valid Parentheses(Java)

来源:互联网 发布:大数据实验室解决方案 编辑:程序博客网 时间:2024/06/05 06:04

https://leetcode.com/problems/longest-valid-parentheses/#/description


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 go.jacob.day707;import java.util.Stack;/** * 32. Longest Valid Parentheses *  * @author Jacob * */public class Demo2 {public int longestValidParentheses(String s) {if (s == null || s.length() < 1)return 0;Stack<Integer> stack = new Stack<Integer>();int max = 0, left = -1;for (int i = 0; i < s.length(); i++) {//如果遍历到左括号,压入堆栈if (s.charAt(i) == '(')stack.push(i);else {if (!stack.isEmpty()) {stack.pop();if (!stack.isEmpty())max = Math.max(max, i - stack.peek());elsemax = Math.max(max, i - left);} else//如果堆栈为空,说明当前的有括号无法配对,需要重新设置left的值left = i;}}return max;}}





原创粉丝点击