栈和队列
232. 用栈实现队列
class MyQueue {
private Stack<Integer> stackIn, 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 t = this.pop();
stackOut.push(t);
return t;
}
public boolean empty() {
if (stackOut.empty() && stackIn.empty()) return true;
else 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. 用队列实现栈
class MyStack {
private Queue<Integer> queueIn;
private Queue<Integer> queueOut;
public MyStack() {
queueIn = new LinkedList<>();
queueOut = new LinkedList<>();
}
public void push(int x) {
if (queueIn.isEmpty())
queueIn.offer(x);
else {
while (!queueIn.isEmpty()) {
queueOut.offer(queueIn.poll());
}
queueIn.offer(x);
while (!queueOut.isEmpty()) {
queueIn.offer(queueOut.poll());
}
}
}
public int pop() {
return queueIn.poll();
}
public int top() {
return queueIn.peek();
}
public boolean empty() {
return queueIn.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. 有效的括号
自己写
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<>();
char[] a = s.toCharArray();
for (char c : a) {
//栈为空直接放入
if (stack.isEmpty()) {
stack.offerFirst(c);
} else if ((stack.peekFirst().equals('{') && c == '}') || (stack.peekFirst().equals('[') && c == ']') || (stack.peekFirst().equals('(') && c == ')')){
//匹配则弹出,不匹配则放入
stack.pollFirst();
} else {
stack.offerFirst(c);
}//else
}//for
//循环结束,栈空则括号全匹配
if (stack.isEmpty())
return true;
return false;
}
}
发现效率很低
看了一下卡哥的技巧:在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以了,比左括号先入栈代码实现要简单的多了!修改如下:
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<>();
char[] a = s.toCharArray();
for (char c : a) {
if (c == '{')
stack.offerFirst('}');
else if (c == '[')
stack.offerFirst(']');
else if (c == '(')
stack.offerFirst(')');
else if (stack.isEmpty() || stack.peek() != c)
return false; //当前位右括号,栈空或无左括号匹配,直接返回false
else //匹配
stack.pollFirst();
}//for
//循环结束,栈空则括号全匹配
return stack.isEmpty();
}
}
妙!