833. Find And Replace in String

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
class Solution {
private static class Action {
private final int index;
private final String source;
private final String target;

public Action(int index, String source, String target) {
this.index = index;
this.source = source;
this.target = target;
}
}

public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
List<Action> actionList = new ArrayList<>(indices.length);
for (int i = 0; i < indices.length; i++) {
actionList.add(new Action(indices[i], sources[i], targets[i]));
}

actionList.sort((o1, o2) -> {
int diff = Integer.compare(o1.index, o2.index);
if (diff != 0) {
return diff;
} else {
return Integer.compare(o1.source.length(), o2.source.length());
}
});

StringBuilder sb = new StringBuilder();
int nextIndex = 0;
for (Action action : actionList) {
if (action.index + action.source.length() > s.length()) {
break;
}

if (match(s, action.index, action.source)) {
sb.append(s, nextIndex, action.index);
sb.append(action.target);
nextIndex = action.index + action.source.length();
}
}


if (nextIndex < s.length()) {
sb.append(s.substring(nextIndex));
}
return sb.toString();
}

private boolean match(String s, int i, String source) {
int j = 0;
while (j < source.length()) {
if (s.charAt(i) != source.charAt(j)) {
return false;
}
i++;
j++;
}

return true;
}
}

References

833. Find And Replace in String