代码随想录算法训练营第十天-20有效的括号、1047删除字符串中的所有相邻重复项、150逆波兰表达式求值
Kiml Lv5
  • 前言
    状态:20AC,1047AC,150AC

  • 更新

1
24.05.30 初始记录

初步题解

20 有效的括号

题目链接:(https://leetcode.cn/problems/valid-parentheses/description/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class LE20 {  
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(isValid(scanner.nextLine()));
}

public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
continue;
}
if (stack.isEmpty()) {
return false;
}
Character pop = stack.pop();
if ((c == ')' && pop != '(' ) || (c == ']' && pop != '[' ) || (c == '}' && pop != '{' )) {
return false;
}
}
return stack.isEmpty();
}
}

1047 删除字符串中的所有相邻重复项

题目链接:(https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static void main(String[] args) {  
Scanner scanner = new Scanner(System.in);
System.out.println(removeDuplicates(scanner.nextLine()));
}

public static String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (stack.isEmpty()) {
stack.push(c);
continue;
}
if (c == stack.peek()) {
stack.pop();
} else {
stack.push(c);
}
}

StringBuilder str = new StringBuilder();
int size = stack.size();
for (int i = 0; i < size; i++) {
str.insert(0, stack.pop());
}
return str.toString();
}

150 逆波兰表达式求值

题目链接:(https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/)

可以直接根据题目中给的链接查看 逆波兰表示法 的意思

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public int evalRPN(String[] tokens) {  
Stack<Integer> stack = new Stack<>();
int num = Integer.parseInt(tokens[0]);
for (String token : tokens) {
switch (token) {
case "+": {
num = stack.pop() + stack.pop();
stack.push(num);
break;
}
case "-": {
Integer num2 = stack.pop();
Integer num1 = stack.pop();
num = num1 - num2;
stack.push(num);
break;
}
case "*": {
num = stack.pop() * stack.pop();
stack.push(num);
break;
}
case "/": {
Integer num2 = stack.pop();
Integer num1 = stack.pop();
num = num1 / num2;
stack.push(num);
break;
}
default: {
stack.push(Integer.parseInt(token));
}
}
}
return num;
}

看解析

20 有效的括号

题目链接/文章讲解/视频讲解:(https://programmercarl.com/0020.有效的括号.html)

1047 删除字符串中的所有相邻重复项

题目链接/文章讲解/视频讲解:(https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html)

150 逆波兰表达式求值

题目链接/文章讲解/视频讲解:(https://programmercarl.com/0150.逆波兰表达式求值.html)

 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep
访客数 访问量