第五章 栈与队列part01
232.用栈实现队列
Leetcode链接: 用栈实现队列
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() {
if(stackOut.empty()){
while(!stackIn.empty()){
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
public int peek() {
if(stackOut.empty()){
while(!stackIn.empty()){
stackOut.push(stackIn.pop());
}
}
return stackOut.peek();
}
public boolean empty() {
if(stackOut.empty() && stackIn.empty()){
return true;
}else{
return false;
}
}
}
这个stack其实有点像翻转array之类的。因为Stack的特性是LIFO(last in first out),但是Queue是FIFO(first in first Out)。所以我们就需要使用两个stack,把所有加入的先push到第一个stack里面去,然后从第一个stack里面push到第二个stack里面。这样先出来的就是last。
225. 用队列实现栈
Leetcode链接: 用队列实现栈
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int x) {
queue2.offer(x);
while(!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer> temp = queue2;
queue2 = queue1;
queue1 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
要点是在push的时候,整理好顺序。
参考动图:方法一:两个队列
20. 有效的括号
Leetcode链接: 有效的括号
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<Character>();
for (char c: s.toCharArray()) {
if (c == '(' || c == '[' || c == '{'){
stack.push(c);
}else{
if(stack.isEmpty()){
return false;
}
if (c == ')' && stack.peek() != '('){
return false;
}
if (c == '}' && stack.peek() != '{'){
return false;
}
if (c == ']' && stack.peek() != '[') {
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
}
这题最好用stack。
1047. 删除字符串中的所有相邻重复项
Leetcode链接: 删除字符串中的所有相邻重复项
class Solution {
public String removeDuplicates(String s) {
ArrayDeque<Character> stack = new ArrayDeque<>();
for (char c: s.toCharArray()) {
if (!stack.isEmpty() && c == stack.peek()){
stack.pop();
}else{
stack.push(c);
}
}
String str = "";
while(!stack.isEmpty()){
str = stack.pop() + str;
}
return str;
}
}
图片来源链接: link
看完官方的答案之后发现string自己就可以做栈,string有pop和push接口
class Solution {
public String removeDuplicates(String s) {
StringBuffer stack = new StringBuffer();
int top = -1;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (top >= 0 && stack.charAt(top) == ch) {
stack.deleteCharAt(top);
--top;
} else {
stack.append(ch);
++top;
}
}
return stack.toString();
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/solutions/643955/shan-chu-zi-fu-chuan-zhong-de-suo-you-xi-4ohr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
总结
Stack和Queue非常适合和动图一起理解。很看的是个人的思路。很多不会的题目或者不知道这么实现的题目一看动图就明白了。