一、#232.用栈实现队列
关键思路:一个栈用来进,另一个栈用来出,两次折腾,就和最开始进的顺序一致
——————————————————————
–》 队尾 (进) ----------------------------》 队首(出) --》
——————————————————————
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
//初始化
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
//将一个元素放入队列的尾部
public void push(int x) {
stackIn.push(x);
}
//从队首移除元素
public int pop() {
dumpStackIn();
return stackOut.pop();
}
//返回队列首部的元素
public int peek() {
dumpStackIn();
return stackOut.peek();
}
//返回队列是否为空
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
//把栈In的元素依次放入栈Out中
private void dumpStackIn(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
二、#225. 用队列实现栈
关键思路:
思路一:一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
思路二:用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1。
思路一:
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
int size = queue.size();
while(size-- >1){
queue.offer(queue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
三、#20. 有效的括号
关键思路:由于栈结构的特殊性,非常适合做对称匹配类的题目
尽管 Deque 是双端队列,但它提供了栈的所有操作:
- push(E e):将元素压入栈顶(等同于 addFirst(e))。
- pop():从栈顶弹出元素(等同于 removeFirst())。
- peek():查看栈顶元素(等同于 getFirst())。
这些方法完全符合栈的后进先出(LIFO)特性。因此,即使代码中声明的是 Deque,但通过只使用 push、pop 和 peek 等方法,实际上它被用作了一个栈。
“charAt(i)” :用于获取字符串中指定索引位置的字符。
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){
return false;
} else {
deque.pop();
}
}
return deque.isEmpty();
}
}
四、#1047. 删除字符串中的所有相邻重复项
关键思路:栈的目的,就是存放遍历过的元素,当遍历当前的这个元素的时候,去栈里看一下我们是不是遍历过相同数值的相邻元素。
class Solution {
public String removeDuplicates(String s) {
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;
}
}
540

被折叠的 条评论
为什么被折叠?



