-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0833-find-and-replace-in-string.js
More file actions
49 lines (41 loc) · 1.43 KB
/
0833-find-and-replace-in-string.js
File metadata and controls
49 lines (41 loc) · 1.43 KB
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
/**
* Find And Replace In String
* Time Complexity: O(K * (N + K * L_t_max))
* Space Complexity: O(N + K * (L_s_max + L_t_max))
*/
var findReplaceString = function (s, indices, sources, targets) {
const replacementOperations = [];
const numOperations = indices.length;
for (
let operationIterator = 0;
operationIterator < numOperations;
operationIterator++
) {
const currentReplacementIndex = indices[operationIterator];
const currentSourceString = sources[operationIterator];
const currentTargetString = targets[operationIterator];
const currentSourceLength = currentSourceString.length;
const subStringToCheck = s.substring(
currentReplacementIndex,
currentReplacementIndex + currentSourceLength,
);
if (subStringToCheck === currentSourceString) {
replacementOperations.push({
index: currentReplacementIndex,
source: currentSourceString,
target: currentTargetString,
});
}
}
replacementOperations.sort((a, b) => b.index - a.index);
let finalString = s;
for (const opDetail of replacementOperations) {
const opIdx = opDetail.index;
const opSrcLen = opDetail.source.length;
const opTgtVal = opDetail.target;
const stringPartBefore = finalString.substring(0, opIdx);
const stringPartAfter = finalString.substring(opIdx + opSrcLen);
finalString = stringPartBefore + opTgtVal + stringPartAfter;
}
return finalString;
};