华为OD机试真题 - 最大括号深度
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word = in.nextLine();
System.out.println(getResult(word));
}
public static int getResult(String word) {
Stack stacks = new Stack<>();
int max = 0;
boolean isInvalid = false;
for (int i = 0; i < word.length(); i++) {
switch (word.charAt(i)) {
case '(' : {
stacks.add('(');
max = Math.max(max, stacks.size());
} break;
case '[' : {
stacks.add('[');
max = Math.max(max, stacks.size());
} break;
case '{' : {
stacks.add('{');
max = Math.max(max, stacks.size());
} break;
case ')' : {
if (stacks.pop() != '(')
isInvalid = true;
break;
}
case ']' : {
if (stacks.pop() != '[')
isInvalid = true;
break;
}
case '}' : {
if (stacks.pop() != '{')
isInvalid = true;
break;
}
default:break;
}
}
if (isInvalid) return 0;
return max;
}
Scanner in = new Scanner(System.in);
String word = in.nextLine();
System.out.println(getResult(word));
}
public static int getResult(String word) {
Stack
int max = 0;
boolean isInvalid = false;
for (int i = 0; i < word.length(); i++) {
switch (word.charAt(i)) {
case '(' : {
stacks.add('(');
max = Math.max(max, stacks.size());
} break;
case '[' : {
stacks.add('[');
max = Math.max(max, stacks.size());
} break;
case '{' : {
stacks.add('{');
max = Math.max(max, stacks.size());
} break;
case ')' : {
if (stacks.pop() != '(')
isInvalid = true;
break;
}
case ']' : {
if (stacks.pop() != '[')
isInvalid = true;
break;
}
case '}' : {
if (stacks.pop() != '{')
isInvalid = true;
break;
}
default:break;
}
}
if (isInvalid) return 0;
return max;
}
全部评论
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享