1. LC 2645 构造有效字符串的最少插入数
这题模拟栈即可,不需要真的用,因为一直访问的都是栈顶元素,所以维护一个栈顶指针即可。
维护下一个需要使用到的元素。例如上一个是a,那么下一个就是b。如果上一个是c,那么下一个是a。取余即可。
如果当前元素位于这个应有的元素后方,那么需要补齐中间的;如果在前方,说明上一轮abc还有缺,需要补上;如果正好就是这个应有元素,那么看下一个字符即可。
时间O(n)空间O(1)
class Solution {
static int mod = 3;
public int addMinimum(String word) {
char[] ch = word.toCharArray();
int top=0,dis;
int cnt = 0;
int index = 0;
while(index<ch.length){
char c = ch[index];
dis = c-'a';
if(dis==top){
top = (top+1)%mod;
index++;
}else{
if(dis>top){
cnt += dis-top;
}else{
cnt += mod+dis-top;
}
top = dis;
}
}
if(top!=0){
cnt += mod - top;
}
return cnt;
}
}
2. LC 225 用队列实现栈
用两个队列实现栈(假设两个队列分别为q1,q2):
- push:把q1中剩下的元素全部push到q2里面去,然后把新元素放到q1里面去。
- pop:先把q1中的元素拿出来(push保证了q1中至多有一个元素),把q2中除了最后一个元素全部push到q1中去。然后交换q1,q2,返回一开始poll的值
- top:返回q1中唯一的元素
- empty:q1和q2均为空
核心思想就是,q1中始终只有一个元素作为栈顶元素。q2中全是备用的,每次pop,从q2中拿出最后一个放到q1里面去。
import java.util.ArrayDeque;
import java.util.Queue;
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new ArrayDeque<>();
q2 = new ArrayDeque<>();
}
public void push(int x) {
if(!q1.isEmpty()){
Integer poll = q1.poll();
q2.offer(poll);
}
q1.offer(x);
}
public int pop() {
Integer top = q1.poll();
while(q2.size()>1){
q1.offer(q2.poll());
}
Queue<Integer> tmp;
tmp = q1;
q1 = q2;
q2 = tmp;
return top;
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty()&&q2.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();
*/
3. LC 232 用栈实现队列
和225一样,第一个栈仅存储一个元素作为队列首部。
-
如果要入队,首先先检查第一个是否为空。
- 如果为空,则直接入第一个栈
- 否则,先把第二个栈的元素暂存到第一个栈,把当前元素推到第二个栈,然后把第一个栈中的元素还原到第二个栈,举个例子:
stk1 = [1] stk2 = [3,2] 新增4 stk1 = [1,2,3] stk2 = [4] stk1 = [1] stk2 = [4,3,2]
-
出队比较简单。把第一个栈的栈顶取出,如果第二个栈还有元素,顶到第一个栈里。
import java.util.Stack;
class MyQueue {
Stack<Integer> stk1;
Stack<Integer> stk2;
public MyQueue() {
stk1 = new Stack<>();
stk2 = new Stack<>();
}
public void push(int x) {
if(stk1.isEmpty()){
stk1.push(x);
return;
}
int size = stk2.size();
while(!stk2.isEmpty()){
stk1.push(stk2.pop());
}
stk2.push(x);
for (int i = 0; i < size; i++) {
stk2.push(stk1.pop());
}
}
public int pop() {
Integer pop = stk1.pop();
if(!stk2.isEmpty()){
stk1.push(stk2.pop());
}
return pop;
}
public int peek() {
return stk1.peek();
}
public boolean empty() {
return stk1.isEmpty()&&stk2.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();
*/