You are given a 0-indexed string s that you must perform k replacement operations on. The replacements are given as three 0-indexed parallel arrays of equal length: indices, sources, and targets.
To complete the i-th replacement operation, check if the substring sources[i] occurs at index indices[i] in the original string s. If it does not occur, do nothing. Otherwise, replace that occurrence of sources[i] with targets[i].
For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement would be "eeecd".
All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The inputs are generated such that the replacements will not overlap.
Return the resulting string after performing all replacement operations on s.
Function Signature
def find_replace_string(s: str, indices: list[int], sources: list[str], targets: list[str]) -> str:
Rules
-
Every match check and every index refers to the original
s
, never to a partly edited string.
-
indices
may be given in any order, and its values are distinct.
-
A source that would extend past the end of
s
does not match, so that operation does nothing.
-
Replacements that succeed never overlap, so the result is unique.
Constraints
-
1 <= len(s) <= 1000
-
0 <= len(indices) <= len(s)
-
0 <= indices[i] < len(s)
-
len(sources) == len(indices)
-
len(targets) == len(indices)
-
1 <= len(sources[i]), len(targets[i]) <= 50
-
s
,
sources[i]
, and
targets[i]
consist of only lowercase English letters.
-
All values of
indices
are distinct.
Examples
Input: s = "abcd", indices = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: "eeebffff"
"a" occurs at index 0 in s, so it becomes "eee". "cd" occurs at index 2, so it becomes "ffff". The untouched "b" stays between them.
Input: s = "abcd", indices = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
"ab" occurs at index 0, so it becomes "eee". "ec" does not occur at index 2 (the original string has "cd" there), so that operation does nothing.
Input: s = "abcd", indices = [2,0], sources = ["cd","a"], targets = ["x","yy"]
Output: "yybx"
The operations are listed out of order, but both positions refer to the original string. "a" at index 0 becomes "yy" and "cd" at index 2 becomes "x".