-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstamping-the-sequence.java
67 lines (52 loc) · 1.32 KB
/
stamping-the-sequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.ArrayList;
import java.util.List;
class Solution {
public int[] movesToStamp(String stamp, String target) {
char[] s = stamp.toCharArray();
char[] t = target.toCharArray();
int n = t.length;
int m = s.length;
List<Integer> res = new ArrayList<>();
boolean[] visited = new boolean[n];
int count = 0;
while (count < n) {
boolean replaced = false;
for (int i = 0; i <= n - m; i++) {
if (!visited[i] && canReplace(t, i, s)) {
count = replace(t, i, m, count);
replaced = true;
visited[i] = true;
res.add(i);
if (count == n) {
break;
}
}
}
if (!replaced) {
return new int[0];
}
}
int[] ans = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
ans[i] = res.get(res.size() - i - 1);
}
return ans;
}
private boolean canReplace(char[] t, int start, char[] s) {
for (int i = 0; i < s.length; i++) {
if (t[i + start] != '?' && t[i + start] != s[i]) {
return false;
}
}
return true;
}
private int replace(char[] t, int start, int len, int count) {
for (int i = 0; i < len; i++) {
if (t[i + start] != '?') {
t[i + start] = '?';
count++;
}
}
return count;
}
}