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() {
if (stackOut.isEmpty()){
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
public int peek() {
int pop = pop();
stackOut.push(pop);
return pop;
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
}
/**
* 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. 用队列实现栈
关键点:队列多次pop、add
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new ArrayDeque<>();
}
public void push(int x) {
queue.add(x);
}
public int pop() {
int size = queue.size() - 1;
while (size-- > 0) {
queue.add(queue.poll());
}
return queue.poll();
}
public int top() {
int size = queue.size() - 1;
while (size-- > 0) {
queue.add(queue.poll());
}
//⏰ 队列的栈尾元素顺序相当于栈的出栈顺序,所以top()读一次栈顶元素后,要将读取的元素重新add一次,恢复其结构
Integer poll = queue.poll();
queue.add(poll);
return poll;
}
public boolean empty() {
return queue.isEmpty();
}
}
20. 有效的括号
关键点:用栈实现匹配问题
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
//三种i情况:1.左括号多了(此时栈不为空)2.右括号不匹配(栈顶元素和当前括号不匹配)3.右括号多余(栈不为空)
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '{') {
stack.add('}');
} else if (s.charAt(i) == '[') {
stack.add(']');
} else if (s.charAt(i) == '(') {
stack.add(')');
}else if(stack.isEmpty() || s.charAt(i) != stack.peek()){
return false;
}else {
stack.pop();
}
}
return stack.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
关键点:条件范围考虑首次的情况
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack();
for(int i=0; i<s.length();i++){
//⏰add()的情况分为不相等和首次放置元素(栈为null),写条件的时候注意逻辑(我本来条件是stack.peek() == s.charAt(i)->pop,否则add,但这样漏了首次的情况)
if(stack.isEmpty() || stack.peek() != s.charAt(i)){
stack.add(s.charAt(i));
}else{
stack.pop();
}
}
//⏰返回为String 但结构为Character,可以选择str = pop+str这种形式
String str = "";
while(!stack.isEmpty()){
Character pop = stack.pop();
str = pop+str;
}
return str;
}
}