华为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;
}
全部评论
相关推荐
07-22 15:24
广西师范大学 大数据开发工程师 上周偶然刷到了lls的26秋招提前批开了,主包前段时间从字节实习完,秉持着投着试试的心态,认真填写了秋招的网申,提交成功的下一秒再刷新应聘页面,已经变成流程结束好夸张!是不是被机筛了,终究是双非不配了

点赞 评论 收藏
分享

点赞 评论 收藏
分享
点赞 评论 收藏
分享