Requirements:

  1. An empty string is a legal parenthesis matching sequence
  2. If X and Y are legitimate sequences, then so is XY
  3. If X is a legitimate matching sequence, then so is delta of X
  4. Each sequence of legal parentheses can be generated by the above rules.

Ideas:

  1. The depth of the empty string is 0
  2. If the depth of X is X and the depth of Y is Y, then the depth of XY is Max (X, Y).
  3. If the depth of X is X, then the depth of X is X plus 1
  4. Iterate backwards from the first character, hitting ‘(‘,count+1, otherwise count-1. Save with Max, Max = math.max (Max, count), Max saves the maximum value of the last loop each time.

Example:

Input: (()) Output: 2Copy the code

Code:

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int cnt = 0, max = 0, i;
        for (i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                cnt++;
            } else{ cnt--; } max = Math.max(max, cnt); } sc.close(); System.out.println(max); }}Copy the code