Find And Replace In String Problem
Description
LeetCode Problem 833.
You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.
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 if it does occur, replace that substring with targets[i].
For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement will be "eeecd".
All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.
- For example, a testcase with s = "abc", indices = [0, 1], and sources = ["ab","bc"] will not be generated because the "ab" and "bc" replacements overlap.
Return the resulting string after performing all replacement operations on s.
A substring is a contiguous sequence of characters in a string.
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.
Constraints:
- 1 <= s.length <= 1000
- k == indices.length == sources.length == targets.length
- 1 <= k <= 100
- 0 <= indexes[i] < s.length
- 1 <= sources[i].length, targets[i].length <= 50
- s consists of only lowercase English letters.
- sources[i] and targets[i] consist of only lowercase English letters.
Solution
Approach: Mark Matches, Then Rebuild
Applying the replacements one by one is awkward, because each replacement shifts the positions of everything after it. Since all operations refer to the original string, we can avoid that entirely: first decide which operations apply, then build the answer in one left-to-right pass.
- Make an array
opAtof lengthn, filled with-1. - For each operation
op, check whethersources[op]occurs insstarting atindices[op]. If it does, setopAt[indices[op]] = op. - Walk through
swith an indexi:- If
opAt[i]is an operation, append its target and jumpiforward by the length of its source. - Otherwise append
s[i]and move toi + 1.
- If
The operations can come in any order, and the array indexed by position takes care of that without sorting. Two operations may share an index; the replacements never overlap, so at most one of them matches there, and only a match is recorded. A source that would run past the end of s simply does not match.
Complexity: O(n + k · m) time and O(n + k · m) space for the result, where n is the length of s, k is the number of operations and m is the maximum length of a source or target.
class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
# op_at[i] = the operation whose source really occurs at index i of the original s, or -1
op_at = [-1] * len(s)
for op, start in enumerate(indices):
if s.startswith(sources[op], start):
op_at[start] = op
parts = []
i = 0
while i < len(s):
op = op_at[i]
if op >= 0:
parts.append(targets[op])
i += len(sources[op]) # skip the replaced characters
else:
parts.append(s[i])
i += 1
return "".join(parts)