1 class Solution { 2 public int longestValidParentheses(String s) { 3 if(s.length() == 0) return 0; 4 char[] arr = s.toCharArray(); 5 Stack<Integer> stack = new Stack<>(); 6 int max = 0; 7 for(int i = 0; i < s.length(); i++){ 8 char c = s.charAt(i); 9 if(c == ‘(‘){ 10 stack.push(i); 11 }else if(c == ‘)‘ && !stack.isEmpty() && s.charAt(stack.peek()) == ‘(‘){ 12 stack.pop(); 13 }else{ 14 stack.push(i); 15 } 16 } 17 if(stack.isEmpty()) return s.length(); 18 int a = s.length(); 19 while(!stack.isEmpty()){ 20 int b = stack.pop(); 21 max = Math.max(max, a-b-1); 22 a = b; 23 } 24 max = Math.max(a, max); 25 return max; 26 27 28 } 29 }
原文:https://www.cnblogs.com/goPanama/p/9863988.html