什么时候使用哈希法?
当我们需要查询一个元素是否出现过,或者一个元素是否在集合里的时候,就要第一时间想到哈希法。
20. 有效的括号
思路
- 括号匹配是使用栈解决的经典问题
- 技巧,在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以
代码
class Solution {
public boolean isValid(String s) {
Deque<Character> deque = new LinkedList<>();
/*在这里,deque 是一个 Deque<Character> 类型的对象,表示一个字符类型的双端队列。通过 new LinkedList<>() 创建了一个 LinkedList 类的实例,并将其赋值给 deque,从而实现了一个基于链表的双端队列。*/
char c;
int size = s.length();
for(int i = 0; i < size; i++){
c = s.charAt(i);
if(c == '['){
deque.push(']');
}else if(c == '{'){
deque.push('}');
}else if(c == '('){
deque.push(')');
}else if(deque.isEmpty() || c != deque.pop()){//isEmpty() 方法调用要加括号!
return false;
}else{
return true;
}
}
if(deque.isEmpty()){
return true;
}else{
return false;//直接输出return deque.isEmpty();
}
}
}
1047. 删除字符串中的所有相邻重复项
思路
- 匹配相邻元素,再消除 栈
代码
class Solution {
public String removeDuplicates(String s) {
StringBuffer res = new StringBuffer();
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();
}
}