LC.P833[字符串中的查找与替换]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
int k = indices.length, n = s.length();
int[] replace = new int[n];
Arrays.fill(replace, -1);
for (int i = 0; i < k; ++i) {
int index = indices[i];
if (s.startsWith(sources[i], index)) {
replace[index] = i;
}
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n; ) {
if (replace[i] >= 0) {
builder.append(targets[replace[i]]);
i += sources[replace[i]].length();
} else {
builder.append(s.charAt(i++));
}
}
return builder.toString();
}
}
  • 时间复杂度:$O(L)$,$L$为所有字符串的长度
  • 空间复杂度:$O(n)$