32. Longest Valid Parentheses
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.
用栈来解决匹配问题,遇到(入栈,遇到)出栈,出栈后分两种情况来算最长匹配段,当栈不为空时,那么直接当前位置-栈顶位置,如果为空,那么就需要记录最长匹配段的开始位置,并用i-开始位置
public class Solution { public int longestValidParentheses(String s) { int begin=0; int res=0; Stack<Integer> stack=new Stack<Integer>(); for (int i=0;i<s.length();i++){ if ("(".equals(s.substring(i,i+1))){ stack.push(i); }else { if (stack.empty()){ begin=i+1; }else { stack.pop(); if (stack.empty()){ res=Math.max(res,i-begin+1); }else { res=Math.max(res,i-stack.peek()); } } } } return res; } }
浙公网安备 33010602011771号