/* * 32. Longest Valid Parentheses * 2016-4-18 by Mingyang * 那么这里我用stack里面装的是index而不是实际的括号 * 实际代码如题,很简单 */
public int longestValidParentheses(String s) { Stack<Integer> stack = new Stack<Integer>(); int max=0; int left = -1; for(int j=0;j<s.length();j++){ if(s.charAt(j)=='(') stack.push(j); else { if (stack.isEmpty()) left=j; else{ stack.pop(); if(stack.isEmpty()) max=Math.max(max,j-left); else max=Math.max(max,j-stack.peek()); } } } return max; }