232 用栈实现队列
栈的一些基本操作:栈的基本操作
class MyQueue {
private Stack<Integer> in;
private Stack<Integer> out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void push(int x) {
in.push(x);
}
public int pop() {
while(!in.isEmpty()) {
out.push(in.pop());
}
int res = out.pop();
while(!out.isEmpty()) {
in.push(out.pop());
}
return res;
}
public int peek() {
while(!in.isEmpty()) {
out.push(in.pop());
}
int res = out.peek();
while(!out.isEmpty()) {
in.push(out.pop());
}
return res;
}
public boolean empty() {
return in.isEmpty() && out.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 用队列实现栈
队列的一些基本操作:队列的基本操作
class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
while(!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
queue1.add(x);
while(!queue2.isEmpty()) {
queue1.offer(queue2.poll());
}
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.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) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
continue;
}
if (stack.isEmpty()) {
return false;
}
Character c1 = stack.pop();
if (c == ')') {
if (c1 == '(') {
continue;
} else {
return false;
}
}
if (c == ']') {
if (c1 == '[') {
continue;
} else {
return false;
}
}
if (c == '}') {
if (c1 == '{') {
continue;
} else {
return false;
}
}
}
return stack.isEmpty();
}
}
1047 删除字符串
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (stack.isEmpty()) {
stack.push(c);
continue;
}
while (!stack.isEmpty()) {
if (stack.peek() == c) {
stack.pop();
break;
} else {
stack.push(c);
break;
}
}
}
int size = stack.size();
if (size == 0) {
return "";
}
char[] res = new char[size];
int i = size - 1;
while(!stack.isEmpty()) {
res[i--] = stack.pop();
}
return String.valueOf(res);
}
}