20.有效的括号
关键点1:将左边各类括号的对应有括号入栈,对比后续的括号与栈内的括号
class Solution {
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 ){
// 栈内元素为空,即左边不够 || 栈内元素不等于此刻的ch
return false;
}else{
deque.pop();
}
}
// 栈内元素有多,右边有多
return deque.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
关键点1:利用入栈的元素和后续元素进行对比,如果等于栈口元素,则将栈口元素出栈,实现相同元素的消除,栈内最后剩下的元素,就是不重复的元素
关键点2:用字符串逆序拼接,完成栈内元素的倒叙
class Solution {
public String removeDuplicates(String s) {
Deque<Character> deque = new LinkedList<>();
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;
}
}
150. 逆波兰表达式求值
关键点1:用栈实现,遇到数字则入栈;
关键点2:遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中
关键点3:减法和除法要做一下数字转换,因为栈是先入后出,所以想实现栈内元素A-B,因为B会先被stack.pop()出来,因此需要:-B+A
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();
}
}