-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path833_Find And Replace in String.js
42 lines (39 loc) · 1.11 KB
/
833_Find And Replace in String.js
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
// https://leetcode-cn.com/contest/weekly-contest-84/problems/find-and-replace-in-string/
/**
* @param {string} S
* @param {number[]} indexes
* @param {string[]} sources
* @param {string[]} targets
* @return {string}
*/
var findReplaceString = function (S, indexes, sources, targets) {
let result = '';
let i = 0;
while (i < S.length) {
let index = indexes.indexOf(i);
if (index === -1) {
result += S[i];
} else {
let source = sources[index];
let match = true;
for (let j = 0; j < source.length; j++) {
if (S[j + i] !== source[j]) {
match = false;
break;
}
}
if (match) {
result += targets[index];
i += source.length - 1;
} else {
result += S[i];
}
}
i++;
}
return result;
};
var S = "abcd", indexes = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"];
console.log(findReplaceString(S, indexes, sources, targets)); //eeebffff
var S = "abcd", indexes = [0, 2], sources = ["ab", "ec"], targets = ["eee", "ffff"];
console.log(findReplaceString(S, indexes, sources, targets)); //eeecd