题解 | #括号字符串的最长有效长度#
括号字符串的最长有效长度
https://www.nowcoder.com/practice/335acafb6d5141b7873c4b0f24d53c57
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.next();
Stack<Integer> stack = new Stack();
int maxans = 0;
stack.push(-1);
for(int i = 0; i<s.length();i++){
if(s.charAt(i)=='('){
stack.push(i);
}else{
stack.pop();
if(stack.isEmpty()){
stack.push(i);
}else{
maxans = Math.max(maxans,i-stack.peek());
}
}
}
System.out.println(maxans);
}
}
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.next();
Stack<Integer> stack = new Stack();
int maxans = 0;
stack.push(-1);
for(int i = 0; i<s.length();i++){
if(s.charAt(i)=='('){
stack.push(i);
}else{
stack.pop();
if(stack.isEmpty()){
stack.push(i);
}else{
maxans = Math.max(maxans,i-stack.peek());
}
}
}
System.out.println(maxans);
}
}