import java.util.ArrayDeque;
import java.util.Deque;
public class BracketDemo {
static boolean matched(String expr) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : expr.toCharArray()) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
if (stack.poll() == null) return false; // 右括号多余
}
}
return stack.isEmpty(); // 还剩左括号说明不匹配
}
public static void main(String[] args) {
System.out.println(matched("(a(b)c)")); // true
System.out.println(matched(")(")); // false
System.out.println(matched("(()")); // false
}
}
步骤 3:PriorityQueue 求 Top-K
新建 TopKDemo.java:
import java.util.Comparator;
import java.util.PriorityQueue;
public class TopKDemo {
public static void main(String[] args) {
// 小顶堆:堆顶是当前最小值,超过 3 个就淘汰最小,最终留下最大的 3 个
PriorityQueue<Integer> top3 = new PriorityQueue<>(Comparator.naturalOrder());
for (int v : new int[]{50, 10, 90, 30, 70, 20}) {
top3.offer(v);
if (top3.size() > 3) top3.poll();
}
System.out.println(top3); // [50, 70, 90]
}
}
步骤 4:亲眼感受 O(n) 与 O(1) 的差距
新建 ContainsDemo.java:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ContainsDemo {
public static void main(String[] args) {
int n = 100_000;
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) { list.add(i); set.add(i); }
long t1 = System.nanoTime();
for (int i = 0; i < 10_000; i++) list.contains(i);
System.out.println("List.contains: " + (System.nanoTime() - t1) / 1_000_000 + " ms");
long t2 = System.nanoTime();
for (int i = 0; i < 10_000; i++) set.contains(i);
System.out.println("Set.contains: " + (System.nanoTime() - t2) / 1_000_000 + " ms");
}
}
List 版本通常耗时是 Set 版本的几十到几百倍——这就是白名单、去重必须用 Set 的量化理由。