20 有效的括号
三种错误情况:
遍历括号,遇到左括号时,向栈里添加右括号,遇到右括号时, 栈顶弹出右括号
遍历完,栈为空时,表示匹配成功
没遍历完,栈为空时,表示有多余的右括号,匹配失败
剪枝:如果字符串长度为奇数,匹配失败
代码思路:
遇到左括号时,向栈里添加元素
遇到右括号时,去栈里的栈顶去匹配,不等于则return false, 相等则pop
遇到右括号时,如果栈为空,说明没有对应的左括号,return false
注意:先判断栈为空,再判断匹配情况
如果遍历完,栈不为空,说明左括号多了,return false
题解
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) return false;
Deque<Character> queue = new LinkedList<>();
char ch;
for (int i = 0; i < s.length(); i ++) {
ch = s.charAt(i);
//碰到左括号,就把相应的右括号入栈
if (ch == '(') {
queue.push(')');
} else if (ch == '{') {
queue.push('}');
} else if (ch == '[') {
queue.push(']');
} else if (queue.isEmpty() || queue.peek() != ch) {
return false;
} else {
queue.pop();
}
}
return queue.isEmpty();
}
}
1047 删除字符串中的所有相邻重复项
思路
将遍历过的元素保存到栈里,
保存的时候和栈顶比较,相同则pop,不同则入栈
使用字符串来模拟栈,可以省去栈转为字符串的操作
题解
栈
class Solution {
public String removeDuplicates(String S) {
//ArrayDeque会比LinkedList在除了删除元素这一点外会快一点
//参考:https://stackoverflow.com/questions/6163166/why-is-arraydeque-better-than-linkedlist
ArrayDeque<Character> deque = new ArrayDeque<>();
char ch;
for (int i = 0; i < S.length(); i++) {
ch = S.charAt(i);
if (deque.isEmpty() || deque.peek() != ch) {
deque.push(ch);
} else {
deque.pop();
}
}
String str = "";
//剩余的元素即为不重复的元素
while (!deque.isEmpty()) {
str = deque.pop() + str;
}
return str;
}
}
字符串模拟栈
class Solution {
public String removeDuplicates(String s) {
// 将 res 当做栈
// 也可以用 StringBuilder 来修改字符串,速度更快
// StringBuilder res = new StringBuilder();
StringBuffer res = new StringBuffer();
// top为 res 的长度
int top = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 当 top > 0,即栈中有字符时,当前字符如果和栈中字符相等,弹出栈顶字符,同时 top--
if (top >= 0 && res.charAt(top) == c) {
res.deleteCharAt(top);
top--;
// 否则,将该字符 入栈,同时top++
} else {
res.append(c);
top++;
}
}
return res.toString();
}
}
150 逆波兰表达式求值
思路
后序遍历:左右中
遇到数字就加入栈里,遇到操作符就出栈,运算后将结果入栈,
最后结果为栈里的元素。
题解
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();
}
}