代码随想录训练营二刷第十一天 | 20. 有效的括号 1047. 删除字符串中的所有相邻重复项 150. 逆波兰表达式求值
一、20. 有效的括号
题目链接:https://leetcode.cn/problems/valid-parentheses/
思路:思路遇到左括号把对应的右括号压入栈,节省后续判断。
class Solution {public static boolean isValid(String s) {LinkedList<Character> stack = new LinkedList<>();for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '[') {stack.push(']');}else if (s.charAt(i) == '{') {stack.push('}');}else if (s.charAt(i) == '(') {stack.push(')');}else if (stack.isEmpty() || stack.peek() != s.charAt(i)) {return false;}else {stack.pop();}}return stack.isEmpty();}
}
二、1047. 删除字符串中的所有相邻重复项
题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
思路:简单的匹配
public String removeDuplicates(String s) {LinkedList<Character> stack = new LinkedList<>();for (int i = 0; i < s.length(); i++) {if (stack.isEmpty() || stack.peek() != s.charAt(i)) {stack.push(s.charAt(i));}else {stack.pop();}}StringBuilder result = new StringBuilder();while (!stack.isEmpty()) {result.insert(0, stack.pop());}return result.toString();}
三、150. 逆波兰表达式求值
题目链接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/
思路:每次出栈,出两个运算再压栈。
class Solution {public int evalRPN(String[] tokens) {LinkedList<Integer> stack = new LinkedList<>();for (int i = 0; i < tokens.length; i++) {if ("+".equals(tokens[i])) {int temp = stack.pop();stack.push(stack.pop() + temp);}else if ("-".equals(tokens[i])) {int temp = stack.pop();stack.push(stack.pop() - temp);}else if ("*".equals(tokens[i])) {int temp = stack.pop();stack.push(stack.pop() * temp);}else if ("/".equals(tokens[i])) {int temp = stack.pop();stack.push(stack.pop() / temp);}else {stack.push(Integer.valueOf(tokens[i]));}}return stack.pop();}
}