#833

Find And Replace in String

specialist · 920 · lc medium +32 · verified · 50.9% accepted · 1,244 likes · top 39%

Description

You are given a 0-indexed string s on which you must perform k replacement operations. The operations are described by three parallel 0-indexed arrays indices, sources, and targets, each of length k.

To perform the ith operation:

- Check whether sources[i] occurs starting at index indices[i] in the original string s.

- If it does not, do nothing.

- If it does, replace that occurrence with targets[i].

For example, with s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", the result is "eeecd".

All operations are applied simultaneously using the original indices, so the replacements never affect each other. The test cases guarantee no overlapping replacements.

Return the resulting string after all replacement operations are applied.

A substring is a contiguous sequence of characters.

Example 1:

Input: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
Output: "eeebffff"
Explanation:
"a" occurs at index 0 in s, so we replace it with "eee".
"cd" occurs at index 2 in s, so we replace it with "ffff".

Example 2:

Input: s = "abcd", indices = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation:
"ab" occurs at index 0 in s, so we replace it with "eee".
"ec" does not occur at index 2 in s, so we do nothing.

Code

1
2
3