|
| 1 | +package com.smlnskgmail.jaman.leetcodejava.hard; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +// https://leetcode.com/problems/stamping-the-sequence/ |
| 6 | +public class StampingTheSequence { |
| 7 | + |
| 8 | + private final String stamp; |
| 9 | + private final String target; |
| 10 | + |
| 11 | + public StampingTheSequence(String stamp, String target) { |
| 12 | + this.stamp = stamp; |
| 13 | + this.target = target; |
| 14 | + } |
| 15 | + |
| 16 | + public int[] solution() { |
| 17 | + int m = stamp.length(); |
| 18 | + int n = target.length(); |
| 19 | + Queue<Integer> q = new ArrayDeque<>(); |
| 20 | + boolean[] done = new boolean[n]; |
| 21 | + Stack<Integer> s = new Stack<>(); |
| 22 | + List<Node> nodes = new ArrayList<>(); |
| 23 | + for (int i = 0; i <= n - m; i++) { |
| 24 | + var made = new HashSet<Integer>(); |
| 25 | + var todo = new HashSet<Integer>(); |
| 26 | + for (int j = 0; j < m; j++) { |
| 27 | + int res = i + j; |
| 28 | + if (target.charAt(res) == stamp.charAt(j)) { |
| 29 | + made.add(res); |
| 30 | + } else { |
| 31 | + todo.add(res); |
| 32 | + } |
| 33 | + } |
| 34 | + nodes.add(new Node(made, todo)); |
| 35 | + if (todo.isEmpty()) { |
| 36 | + s.push(i); |
| 37 | + for (int j = i; j < i + m; j++) { |
| 38 | + if (!done[j]) { |
| 39 | + q.add(j); |
| 40 | + done[j] = true; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + while (!q.isEmpty()) { |
| 46 | + int i = q.poll(); |
| 47 | + for (int j = Math.max(0, i - m + 1); j <= Math.min(n - m, i); j++) { |
| 48 | + var todo = nodes.get(j).todo; |
| 49 | + if (todo.contains(i)) { |
| 50 | + todo.remove(i); |
| 51 | + if (todo.isEmpty()) { |
| 52 | + s.push(j); |
| 53 | + for (int made : nodes.get(j).made) { |
| 54 | + if (!done[made]) { |
| 55 | + q.add(made); |
| 56 | + done[made] = true; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + for (boolean b : done) { |
| 64 | + if (!b) { |
| 65 | + return new int[0]; |
| 66 | + } |
| 67 | + } |
| 68 | + int[] result = new int[s.size()]; |
| 69 | + int pos = 0; |
| 70 | + while (!s.isEmpty()) { |
| 71 | + result[pos++] = s.pop(); |
| 72 | + } |
| 73 | + return result; |
| 74 | + } |
| 75 | + |
| 76 | + static class Node { |
| 77 | + |
| 78 | + Set<Integer> made; |
| 79 | + Set<Integer> todo; |
| 80 | + |
| 81 | + Node(Set<Integer> made, Set<Integer> todo) { |
| 82 | + this.made = made; |
| 83 | + this.todo = todo; |
| 84 | + } |
| 85 | + |
| 86 | + } |
| 87 | + |
| 88 | +} |
0 commit comments