摘要
本文主要介绍了栈相关的几个LeetCode题目,包括是20. 有效的括号、1047. 删除字符串中的所有相邻重复项、150. 逆波兰表达式求值。
1、20. 有效的括号
1.1 思路
- 使用栈,遍历字符串s
- 当遇到左括号'('、'['、'{',在栈中添加对应的右括号
- 当遇到右括号时,判断栈顶是否存在该右括号,如果不存在返回false
- 最后,如果栈不为空,也返回false
1.2 代码
public boolean isValid(String s) {
LinkedList<Character> stack = new LinkedList<>();
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(ch == '(') {
stack.push(')');
} else if(ch == '[') {
stack.push(']');
} else if(ch == '{') {
stack.push('}');
} else {
if(!stack.isEmpty() && ch == stack.pop()) {
continue;
}
return false;
}
}
return stack.isEmpty();
}
2、1047. 删除字符串中的所有相邻重复项
2.1 思路
- 使用StringBuilder模拟栈,遍历字符串s
- 如果当前元素与栈顶元素相同,则移除栈顶元素,否则加入到栈中
deleteCharAt(length-1):StringBuilder去掉最后一个字符
2.2 代码
public String removeDuplicates(String s) {
StringBuilder builder = new StringBuilder();
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(builder.length() > 0 && builder.charAt(builder.length()-1) == ch) {
builder.deleteCharAt(builder.length()-1);
} else {
builder.append(ch);
}
}
return builder.toString();
}
3、150. 逆波兰表达式求值
3.1 思路
- 使用栈,遍历字符串数组tokens
- 如果当前元素是数字,加入到栈中
- 如果当前元素是运算符,取出靠近栈顶元素的两个元素
- 计算得出结果并加入到栈中准备下一次运算
3.2 代码
public int evalRPN(String[] tokens) {
LinkedList<Integer> stack = new LinkedList<>();
for(String token: tokens) {
if(token.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if(token.equals("-")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2 - num1);
} else if(token.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if(token.equals("/")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2 / num1);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}