题目一:
注意一下题目的要求:进栈的时候是否可以出栈。
题目二:
public int evalRPN(String[] tokens) {
//3. 创建一个栈
Stack<Integer> stack = new Stack<>();
//1. 得到字符串数组中的每一个元素
for (int i = 0; i < tokens.length; i++) {
String cur = tokens[i];
//2. 判断cur是否为操作符
if (!this.isOperation(cur)) {
Integer num = Integer.valueOf(cur);
stack.push(num);
} else {
Integer right = stack.pop();
Integer left = stack.pop();
switch (cur) {
case "+":
stack.push(left + right);
break;
case "-":
stack.push(left - right);
break;
case "*":
stack.push(left * right);
break;
case "/":
stack.push(left / right);
break;
}
}
}
//4. 返回
return stack.pop();
}
public boolean isOperation(String str) {
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) {
return true;
}
return false;
}
题目三:
public boolean isValid(String s) {
//3. 创建一个栈
Stack<Character> stack = new Stack<>();
//1. 遍历字符串中的每个字符
for (int i = 0 ; i < s.length(); i++) {
char ch = s.charAt(i);
//2. 判断是否为左括号
if (this.isLeftBracket(ch)) {
stack.push(ch);
} else {
if (stack.empty()) {
return false;
} else {
char left = stack.peek();
//4. 判断left 和 ch 是否匹配
if ((left == '(' && ch == ')') ||
(left == '{' && ch == '}') ||
(left == '[' && ch == ']')) {
stack.pop();
} else {
return false;
}
}
}
}
//5. 判断栈是否为空,针对所给的字符串全为左括号的情况
if (!stack.empty()) {
return false;
}
return true;
}
public boolean isLeftBracket(char ch) {
if (ch == '(' || ch == '{' || ch == '[') {
return true;
}
return false;
}
题目四:正
栈的压入、弹出序列_牛客题霸_牛客网 (nowcoder.com)
public boolean IsPopOrder (int[] pushV, int[] popV) {
//1. 创建一个栈
Stack<Integer> stack = new Stack<>();
int j = 0;//popV数组的下标
for (int i = 0; i < pushV.length; i++) {
stack.push(pushV[i]);
//🙀栈为空了就不要再peek了,123456,543216
//🙀不需要考虑所给的两个数组长度不一致的问题
while (!stack.empty() && stack.peek() == popV[j]) {
stack.pop();
j++;
}
}
//2. 判断栈是否为空
if (!stack.empty()) {
return false;
} else {
return true;
}
}
题目五:正
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
stack.push(val);
if (minStack.empty()) {
minStack.push(val);
} else {
int minTop = minStack.peek();
if (val <= minTop) {
minStack.push(val);
}
}
}
public void pop() {
if (stack.empty()) {
return;
}
int del = stack.pop();
if (minStack.peek() == del) {
minStack.pop();
}
}
public int top() {
if (stack.empty()) {
return -1;
}
return stack.peek();
}
public int getMin() {
if (minStack.empty()) {
return -1;
}
return minStack.peek();
}
}