版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/87284790
1 判断括号字符串是否有效
https://leetcode.com/problems/valid-parentheses/description/
- 如果一开始是 右括号 就返回 false
- 时间复杂度: 每个元素入栈 O(1), 一共 n 个元素,所以是 O(n)
- 空间复杂度: O(n)
package linked_list_leetcode;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class ValidParentheses_20 {
public static boolean isValid(String s) {
char[] chars = s.toCharArray();
Stack<Character> stack = new Stack<>();
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
for (char c : chars) {
if (!map.containsKey(c)) {
stack.push(c);
} else if (stack.isEmpty() || !map.get(c).equals(stack.pop())) {
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String s = "()";
boolean flag = isValid(s);
System.out.println(flag);
}
}
2 使用栈实现队列
https://leetcode.com/problems/implement-queue-using-stacks/
package linked_list_leetcode;
import java.util.Stack;
public class ImplementQueueUsingStacks_232 {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public void push(int x) {
while (!s2.isEmpty()) {
s1.push(s2.pop());
}
s1.push(x);
}
public int pop() {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.pop();
}
public int peek() {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.peek();
}
public boolean empty(){
return s1.isEmpty() && s2.isEmpty();
}
}
3 使用队列实现栈
https://leetcode.com/problems/implement-stack-using-queues/
package linked_list_leetcode;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class ImplementStackUsingQueues_225 {
Queue<Integer> q1 = new LinkedList<>(); // 主要存放数据
Queue<Integer> q2 = new LinkedList<>(); // 辅助
public void push(int x) {
q1.add(x);
}
public int pop() {
int top = 0;
while (q1.size() > 1) {
q2.add(q1.poll());
}
if (q1.size() == 1) {
top = q1.poll();
while (q2.size() > 0) {
q1.add(q2.poll());
}
}
return top;
}
public int top() {
int top = 0;
while (q1.size() > 1) {
q2.add(q1.poll());
}
if (q1.size() == 1) {
top = q1.poll();
while (q2.size() > 0) {
q1.add(q2.poll());
}
q1.add(top);
}
return top;
}
public boolean empty() {
return q1.size() == 0;
}
}