class Solution {
public boolean isValid(String s) {
Deque<Character> deque = new LinkedList<>();
char c;
for(int i = 0; i < s.length(); i ++){
c = s.charAt(i);
if(c == '('){
deque.push(')');
}else if(c == '{'){
deque.push('}');
}else if(c == '['){
deque.push(']');
}else if(deque.isEmpty() || deque.peek() != c){
return false;
}else{
deque.pop();
}
}
return deque.isEmpty();
}
}
反括号进栈,出栈就只需要比对是否相等
题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution {
public String removeDuplicates(String s) {
Deque<Character> deque = new LinkedList<>();
char c;
for(int i = 0; i < s.length(); i ++){
c = s.charAt(i);
if(deque.isEmpty()){
deque.push(c);
}else if(deque.peek() == c){
deque.pop();
continue;
}else{
deque.push(c);
}
}
if(deque.isEmpty()){
return "";
}
StringBuilder sb = new StringBuilder();
while(!deque.isEmpty()){
sb.insert(0, deque.pop());
}
return sb.toString();
}
}
用栈的思想
题目链接:150. 逆波兰表达式求值 - 力扣(LeetCode)
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> deque = new LinkedList<>();
String c;
int temp;
for(int i = 0; i < tokens.length; i ++){
c = tokens[i];
if(!"+".equals(c) && !"-".equals(c) && !"*".equals(c) && !"/".equals(c)){
deque.push(Integer.parseInt(c));
continue;
}
if("+".equals(c)){
temp = deque.pop() + deque.pop();
deque.push(temp);
}else if("-".equals(c)){
temp = deque.pop() - deque.pop();
deque.push(-temp);
}else if("*".equals(c)){
temp = deque.pop() * deque.pop();
deque.push(temp);
}else if("/".equals(c)){
temp = deque.pop();
deque.push(deque.pop() / temp);
}
}
return deque.pop();
}
}
1.String类型比较用equals,且加减乘除放前面避免空指针异常。“==”比较的是地址
2.减法和除法注意从栈出来两个数的顺序