华为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;
}
全部评论
相关推荐
03-02 17:02
Nanyang Technological University 数据分析师
在改简历的大卫很认真:天天有面试 = 你已经在 offer 门口了。
海投能面成这样,说明你的简历、基础、学历都是过关的,缺的只是一次刚好匹配的缘分。
关于你说的 SQL 恐惧,我帮你捋一下:
- 面试里考来考去,真就那几类:
分组、去重、关联、子查询、窗口函数(row_number、rank、sum 开窗)
- 面试官要的不是“写得花里胡哨”,而是思路稳、不出错。
你恐惧的本质不是不会,
是怕临场卡壳、怕写错、怕被追问。 点赞 评论 收藏
分享
03-10 16:37
蚌埠坦克学院 Java 点赞 评论 收藏
分享