232. 用栈实现队列 - 力扣(LeetCode)
import java.util.Stack;
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.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. 用队列实现栈 - 力扣(LeetCode)
class MyStack {
private Queue<Integer> q1;
private Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(Integer x) {
q1.offer(x);
}
public int pop() {
while (q1.size() > 1) {
q2.offer(q1.poll());
}
int topElement = q1.poll();
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
return topElement;
}
public int top() {
while (q1.size() > 1) {
q2.offer(q1.poll());
}
int topElement = q1.poll();
q2.offer(topElement);
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
return topElement;
}
public boolean empty() {
return q1.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. 有效的括号 - 力扣(LeetCode)
class Solution {
private static final Map<Character, Character> map = new HashMap<Character, Character>() {
{
put('{', '}');
put('[', ']');
put('(', ')');
put('?', '?');
}
};
public boolean isValid(String s) {
if (s.length() > 0 && !map.containsKey(s.charAt(0)))
return false;
LinkedList<Character> stack = new LinkedList<Character>() {
{
add('?');
}
};
for (Character c : s.toCharArray()) {
if (map.containsKey(c))
stack.addLast(c);
else if (map.get(stack.removeLast()) != c)
return false;
}
return stack.size() == 1;
}
}
1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution {
public String removeDuplicates(String s) {
StringBuffer stack = new StringBuffer();
int top = -1;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (top >= 0 && stack.charAt(top) == ch) {
stack.deleteCharAt(top);
--top;
} else {
stack.append(ch);
++top;
}
}
return stack.toString();
}
}
加油。