Requirements:
- An empty string is a legal parenthesis matching sequence
- If X and Y are legitimate sequences, then so is XY
- If X is a legitimate matching sequence, then so is delta of X
- Each sequence of legal parentheses can be generated by the above rules.
Ideas:
- The depth of the empty string is 0
- If the depth of X is X and the depth of Y is Y, then the depth of XY is Max (X, Y).
- If the depth of X is X, then the depth of X is X plus 1
- 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