[Leetcode] 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.

Solution:

http://www.cnphp6.com/archives/43272

leetcode讨论组大牛的方法,使用一个stack,只存左括号的下标,last变量存放最后一个无法匹配的’)’,遍历字符串,如果遇到'(‘,下标就放入栈中,如果入到’)’,则分两种情况,一种是栈为空,那么说明’)’无法被匹配,更新last,另一种栈不为空,那么pop出一个'(‘,此时如果栈为空,说明可以得到完整的符合要求的长度,长度为i-last,如果栈不为空,说明栈还有'(‘没有被匹配,那么目前合法的长度为i-st.top(),时间复杂度为O(n)。

 1 public class Solution {
 2     public int longestValidParentheses(String s) {
 3         if (s == null || s.length() == 0)
 4             return 0;
 5         Stack<Integer> stack = new Stack<Integer>();
 6         int result = 0;
 7         int last=-1;//ans表示最大合法长度,last最后一个无法匹配的')'的下标
 8         for (int i = 0; i < s.length(); ++i) {
 9             if(s.charAt(i)=='('){
10                 stack.push(i);//遇到左括号,就放入左括号的下标
11             }else{//遇到右括号
12                 if(stack.isEmpty()){
13                     last=i;//如果栈空,更新last
14                 }else{//栈非空
15                     stack.pop();//pop出一个'('
16                     if(stack.isEmpty()){//此时如果栈空,那么就是个完整的合法长度,即i-last
17                         result=Math.max(result, i-last);
18                     }else{//如果栈非空,那么局部合法长度即为i-st.top()
19                         result=Math.max(result, i-stack.peek());
20                     }
21                 }
22             }
23         }
24         return result;
25     }
26 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4132726.html