class MyQueue {
// 队列是先进先出,栈是先进后出,所以用两个栈来实现一个队列
private Stack<Integer> in;
private Stack<Integer> out;
/** Initialize your data structure here. */
public MyQueue() { // 初始化
in = new Stack();
out = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x); // 加元素到尾部
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
in2Out();
return out.pop();
}
/** Get the front element. */
public int peek() {
in2Out();
return out.peek(); // 获取第一个元素
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
private void in2Out(){
while(out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
}
}
class MyStack {
/**
队列:尾进头出
栈:头进头出
在将一个元素x插入队列的时候,为了维护原来的后进先出顺序,需要让x插入队列首部,而队列的默认插入顺序是队列的尾部
因此在将x插入队列尾部之后,需要让除了x之外的元素出队列,然后入队列
*/
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
int cnt = queue.size();
while(cnt-- >1){
queue.add(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
class MinStack {
private Stack<Integer> dataStack; // 正常的栈
private Stack<Integer> minStack; // 最小的在最上面
private int min;
/** initialize your data structure here. */
public MinStack() {
dataStack = new Stack<>();
minStack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int val) {
dataStack.push(val);
min = Math.min(min,val);
minStack.push(min);
}
public void pop() {
dataStack.pop();
minStack.pop();
min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
class Solution {
public boolean isValid(String s) {
//利用一个栈来判断,如果是左括号则入栈,如果是右括号,则与栈里面拿出的元素比较
// 第一个右括号,肯定是紧连着对应的左括号
Stack<Character> stack = new Stack<>();
for (int i = 0;i< s.length();i++){
char ch = s.charAt(i);
// 如果是左括号就入栈,如果是右括号就取出栈顶元素对比
if(ch =='(' || ch== '[' || ch=='{'){
stack.push(ch);
}else{
if(stack.isEmpty()) return false;
char si = stack.pop();
if(ch == ')' && si!= '(') return false;
else if(ch == '}' && si!= '{') return false;
else if(ch == ']' && si!= '[') return false;
}
}
return stack.isEmpty();
}
}