LeetCode 20. 有效的括号
题目链接:https://leetcode.cn/problems/valid-parentheses/submissions/533154919/
文章链接:https://programmercarl.com/0020.%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7.html#%E6%80%9D%E8%B7%AF
思路
public boolean isValid(String s) {
Deque<Character> deque = new LinkedList<>();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
//碰到左括号,就把相应的右括号入栈
if (ch == '(') {
deque.push(')');
}else if (ch == '{') {
deque.push('}');
}else if (ch == '[') {
deque.push(']');
} else if (deque.isEmpty() || deque.peek() != ch) {
return false;
}else {//如果是右括号判断是否和栈顶元素匹配
deque.pop();
}
}
//最后判断栈中元素是否匹配
return deque.isEmpty();
}
1047. 删除字符串中的所有相邻重复项
题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/
文章链接:https://programmercarl.com/1047.%E5%88%A0%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E6%89%80%E6%9C%89%E7%9B%B8%E9%82%BB%E9%87%8D%E5%A4%8D%E9%A1%B9.html
思路
我们在删除相邻重复项的时候,其实就是要知道当前遍历的这个元素,我们在前一位是不是遍历过一样数值的元素,那么如何记录前面遍历过的元素呢?所以就是用栈来存放,那么栈的目的,就是存放遍历过的元素,当遍历当前的这个元素的时候,去栈里看一下我们是不是遍历过相同数值的相邻元素。
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())
stack.push(c);
else {
if (stack.peek() == c) {
stack.pop();
}else
stack.push(c);
}
}
StringBuilder str = new StringBuilder();
for (Character character : stack) {
str.append(character);
}
return str.toString();
}
150. 逆波兰表达式求值
题目链接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
文章链接:https://programmercarl.com/0150.%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
思路
思想:遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。最终栈顶元素则为最终结果。
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if ("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token)){
Integer p1 = stack.pop();
Integer p2 = stack.pop();
if ("+".equals(token))
stack.push(p2 + p1);
if ("-".equals(token))
stack.push(p2 - p1);
if ("*".equals(token))
stack.push(p2 * p1);
if ("/".equals(token))
stack.push(p2 / p1);
}else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}