* * 示例 1:
* * 输入: "(()"
* * 输出: 2
* * 解释: 最长有效括号子串为 "()"
* * 示例 2:
* * 输入: ")()())"
* * 输出: 4
* * 解释: 最长有效括号子串为 "()()"
* * 示例 3:
* * 输入: "(())(()"
* * 输出: 6
* * 解释: 最长有效括号子串为 "(())()"
package test;
/**
* @author:
* @description
* @create 2021-07-12 20:01
* @Copyright (C), 2006-2021,
*/
import java.util.Scanner;
import java.util.Stack;
/**
* * 示例 1:
* * 输入: "(()"
* * 输出: 2
* * 解释: 最长有效括号子串为 "()"
* * 示例 2:
* * 输入: ")()())"
* * 输出: 4
* * 解释: 最长有效括号子串为 "()()"
* * 示例 3:
* * 输入: "(())(()"
* * 输出: 6
* * 解释: 最长有效括号子串为 "(())()"
* *
* * class Solution {
* * public int longestValidParentheses(String s) {
* * }
* * }
*/
public class OdTest_02 {
public static void main(String[] args) {
System.out.println(solve(new Scanner(System.in).nextLine()));
}
static int solve(String str) {
int max = 0;
if (str == null) {
return 0;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(') {
stack.push('(');
continue;
} else {
if (stack.isEmpty()) {
continue;
} else {
stack.pop();
max += 2;
}
}
}
return max;
}
}