forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_936.java
64 lines (59 loc) · 2.08 KB
/
_936.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _936 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/stamping-the-sequence/discuss/201546/12ms-Java-Solution-Beats-100
* <p>
* Think reversely!
* How to change target to ****?!
*/
public int[] movesToStamp(String stamp, String target) {
List<Integer> moves = new ArrayList<>();
char[] s = stamp.toCharArray();
char[] t = target.toCharArray();
int stars = 0;
boolean[] visited = new boolean[target.length()];
while (stars < target.length()) {
boolean doneReplace = false;
for (int i = 0; i <= target.length() - stamp.length(); i++) {
if (!visited[i] && canReplace(t, i, s)) {
stars = doReplace(t, i, s, stars);
doneReplace = true;
visited[i] = true;
moves.add(i);
if (stars == t.length) {
break;
}
}
}
if (!doneReplace) {
return new int[0];
}
}
int[] result = new int[moves.size()];
for (int i = 0; i < moves.size(); i++) {
result[i] = moves.get(moves.size() - i - 1);
}
return result;
}
private boolean canReplace(char[] t, int i, char[] s) {
for (int j = 0; j < s.length; j++) {
if (t[i + j] != '*' && t[i + j] != s[j]) {
return false;
}
}
return true;
}
private int doReplace(char[] t, int i, char[] s, int stars) {
for (int j = 0; j < s.length; j++) {
if (t[i + j] != '*') {
t[i + j] = '*';
stars++;
}
}
return stars;
}
}
}