JAVA二刷-Day11 | 20. 有效的括号, 1047. 删除字符串中的所有相邻重复项, 150. 逆波兰表达式求值
有效的括号
LeetCode题目链接:https://leetcode.cn/problems/valid-parentheses/
解题思路
新的右括号一定要和最后的左括号进行比较,因此是LIFO策略的栈进行计算比较合适。
代码如下:
class Solution {
public boolean isValid(String s) {
Stack<Character> stk = new Stack();
for (char a : s.toCharArray()) {
if (a == '('|| a == '{'|| a == '[') {
stk.push(a);
}else if (!stk.empty() && stk.peek() == '(' && a == ')') {
stk.pop();
}else if (!stk.empty() && stk.peek() == '{' && a == '}') {
stk.pop();
}else if (!stk.empty() && stk.peek() == '[' && a == ']') {
stk.pop();
}else {
return false;
}
}
if (stk.empty()) return true;
return false;
}
}
删除字符串中的所有相邻重复项
LeetCode题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
解题思路
要消除相邻重复项,思路和消除相邻的左右括号类似,相同便进行出栈和跳过操作。
具体代码如下:
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stk = new Stack();
for (char a: s.toCharArray()) {
if (stk.empty() || stk.peek() != a) {
stk.push(a);
continue;
}
if (stk.peek() == a) {
stk.pop();
}
}
StringBuilder sb = new StringBuilder();
while (!stk.empty()) {
sb.append(stk.peek());
stk.pop();
}
return sb.reverse().toString();
}
}
逆波兰表达式
LeetCode题目链接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/submissions/
解题思路
逆波兰表达式:
逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。
平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) ∗ ( 3 + 4 ) ( 1 + 2 ) * ( 3 + 4 ) (1+2)∗(3+4)。该算式的逆波兰表达式写法为 ( ( 12 + ) ( 34 + ) ∗ ) ( ( 1 2 + ) ( 3 4 + ) * ) ((12+)(34+)∗) 。
逆波兰表达式主要有以下两个优点:
1、去掉括号后表达式无歧义,上式即便写成
12
+
34
+
∗
1 2 + 3 4 + *
12+34+∗ 也可以依据次序计算出正确结果。
2、适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
因此根据以上特性,可以轻松写出代码,本题应注意的是将string转为int类型变量可以调用Integer.parseInt(String s)。
由于内置jdk的原因,不能使用a == "+"方法比较。
具体代码如下:
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stk = new Stack();
for (String a : tokens) {
if (a.equals("+") || a.equals("-") || a.equals("*") || a.equals("/")) {
int num2 = stk.peek();
stk.pop();
int num1 = stk.peek();
stk.pop();
if (a.equals("+")) {
stk.push(num1 + num2);
}else if (a.equals("-")) {
stk.push(num1 - num2);
}else if (a.equals("*")) {
stk.push(num1 * num2);
}else if (a.equals("/")) {
stk.push(num1 / num2);
}
}else {
stk.push(Integer.parseInt(a));
}
}
return stk.peek();
}
}