LeetCode20、有效的括号
代码
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (c == '('){
stack.push(')');
}else if (c == '['){
stack.push(']');
}else if (c == '{'){
stack.push('}');
}else {
if ((stack.isEmpty()) || (c != stack.peek())){
return false;
}
stack.pop();
}
}
if (stack.isEmpty()){
return true;
}else {
return false;
}
}
}
要点
- 这里要先判断是否为空,再取stack的栈顶值,如果顺序调换的话,如果stack已经空了,但先取栈顶值的话,就会报错了
- for循环结束之后,不能马上返回TRUE,因为有可能for循环结束了,栈还不为空,(对应左边多的情况),此时要返回FALSE
- 总结下来就是三种情况:左边多符号,右边多符号,中间的符号不配对
- ({{}[]})
LeetCode1047、删除字符串中的所有相邻重复项
代码
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if ((stack.isEmpty()) || (c != stack.peek())){
stack.push(c);
}else {
stack.pop();
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
sb = sb.reverse();
return sb.toString();
}
}
要点
这道题绕了好久,把自己绕晕进去了,原来采用的方法是如果空,则push;不空,则进循环
但是总是在八个a的测试用例那里卡住,输出结果怎么改也是要输出1个a,没弄清什么情况。。。
后来换了代码随想录里的思路,push的情况:stack为空或者字母不匹配;pop的情况:else。代码简单还解决了问题。
LeetCode150、逆波兰表达式求值
代码
我的代码
public class Stack150 {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++){
int num1, num2, result;
num2 = 0;
if ((!stack.isEmpty()) && (tokens[i].equals("+"))){
num1 = Integer.parseInt(stack.pop());
if (!stack.isEmpty()){
num2 = Integer.parseInt(stack.pop());
}
result = num1 + num2;
stack.push(String.valueOf(result));
}else if ((!stack.isEmpty()) && (tokens[i].equals("-"))){
num1 = Integer.parseInt(stack.pop());
if (!stack.isEmpty()){
num2 = Integer.parseInt(stack.pop());
}
result = num2 - num1;
stack.push(String.valueOf(result));
}else if ((!stack.isEmpty()) && (tokens[i].equals("*"))){
num1 = Integer.parseInt(stack.pop());
if (!stack.isEmpty()){
num2 = Integer.parseInt(stack.pop());
}
result = num2 * num1;
stack.push(String.valueOf(result));
}else if ((!stack.isEmpty()) && (tokens[i].equals("/"))){
num1 = Integer.parseInt(stack.pop());
if (!stack.isEmpty()){
num2 = Integer.parseInt(stack.pop());
}
result = num2 / num1;
stack.push(String.valueOf(result));
}else {
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.peek());
}
}
代码随想录的代码
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList();
for (String s : tokens) {
if ("+".equals(s)) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等
stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理
} else if ("-".equals(s)) {
stack.push(-stack.pop() + stack.pop());
} else if ("*".equals(s)) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(s)) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}
注意
- 数组的遍历:
for (String s : tokens)
- 入栈的时候转为int入栈,就不用每次进行四则运算操作时再将string转为int了
- 题目不考虑不标准的情况,即不会出现stackpop一次后为空