The straightforward method involves performing a brute-force search to identify all instances of the pattern in the text. Then, we replace each occurrence of the pattern with the specified string. This approach has a time complexity of O(n^2).
To improve the solution, we can use the Knuth-Morris-Pratt (KMP) algorithm to efficiently find all occurrences of the pattern in the text. Unlike the brute-force method, KMP operates in O(n) time. I have discussed the KMP algorithm in detail in another post.
Here’s how we can improve the solution:
Use the KMP algorithm to find all occurrences of the pattern in the text, which takes O(n) time.
Store these positions in an array (let’s call it positionArray).
Utilize a StringBuilder to construct the final string with replacements.
Maintain a pointer (positionPointer) to track the index in positionArray.
Traverse the text from left to right.
Append characters to the StringBuilder, except at positions indicated by positionPointer; here, append the replacement string instead and skip the pattern length in the text.
Adjust positionPointer appropriately to manage overlapping patterns (e.g., in a text like “aaaaaa” with pattern “aa” replaced by “X”).
positions = KMP_SEARCH(text, pattern)
StringBuilder result
positionPointer =0for each character in text:
if positionPointer < length of positions and current index is positions[positionPointer]:
append replacement to result
skip pattern length in text
positionPointer++else:
append current character to result