232.用栈实现队列
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
思路:设置开口在两侧的两个栈模拟队列。
注意事项:只有当out这个栈空的时候才能执行转移的操作,不然会造成混乱。
class MyQueue {
Stack<Integer> stackIn, stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
peek();
return stackOut.pop();
}
public int peek() {
if(stackOut.isEmpty()){
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
return stackOut.peek();
}
public boolean empty() {
if(stackIn.isEmpty() && stackOut.isEmpty()){
return true;
}
return false;
}
}
/**
* 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.用队列实现栈
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
思路:不断把前面的元素放到后面来。
注意事项,size和元素个数的关系。
问题:常识性的基础不牢固,注意stack的API都有什么。
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
}
public int pop() {
int size = queue.size();
while(size - 1 > 0){
queue.add(queue.poll());
size--;
}
return queue.poll();
}
public int top() {
int size = queue.size();
System.out.println(size);
while(size - 1 > 0){
queue.add(queue.poll());
size--;
}
int ret = queue.peek();
queue.add(queue.poll());
return ret;
}
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;
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<Character>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == '(' ){
stack.push(')');
}else if (ch == '['){
stack.push(']');
}else if(ch == '{'){
stack.push('}');
}else if(stack.isEmpty() || stack.pop() != ch){
return false;
}
}
return stack.isEmpty();
}
}
1047.删除相邻重复项
使用栈的思路
要注意判断是否为空
class Solution {
public String removeDuplicates(String s) {
ArrayDeque <Character> stack = new ArrayDeque<>();
char ch;
for(int i = 0; i < s.length(); i ++){
ch = s.charAt(i);
if(!stack.isEmpty() && ch == stack.peek()){
stack.pop();
}else{
stack.push(ch);
}
}
String str = "";
while(!stack.isEmpty()){
str = stack.pop() + str;
}
return str;
}
}