华为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<Character> 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<Character> 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;
}
全部评论
相关推荐

点赞 评论 收藏
分享
09-18 09:22
成都理工大学 Java 重生之我学Java干...:有个疑问,实习生怎么会参与Satoken的接入和数据库加盐这种项目初期设计的工作?这不应该是架构师或者老员工来做么。简历写这个确实有点像包装的
点赞 评论 收藏
分享