![]() |
VOOZH | about |
Given three strings s, s1, and s2 of lengths n, m, and k respectively, the task is to modify the string s by replacing all the substrings s1 with the string s2 in the string s.
Examples:
Input: s = "abababa", s1 = "aba", s2 = "a"
Output: aba
Explanation: Change the substrings s[0, 2] and s[4, 6] to the string s2 modifies the string s to "aba".Input: s = "geeksforgeeks", s1 = "eek", s2 = "ok"
Output: goksforgoks
Explanation: Change the substrings s[1, 3] and s[9, 11] to the string
Table of Content
The simplest approach to solve the given problem is to traverse the string s and when any string s1 is found as a substring in the string s then replace it by s2.
aba
The above approach can also be optimized by creating the longest proper prefix and suffix array for the string s1 and then perform the KMP Algorithm to find the occurrences of the string s1 in the string s.
Algorithm:
aba
Time Complexity: The time complexity is O(n + m), where n is the length of string s and m is the length of string s1.
The LPS function runs in O(m) time to compute the prefix-suffix array, and the main loop processes string s in O(n) time.
Auxiliary Space: The LPS array requires O(m) space, where m is the length of s1, so the overall space complexity is O(m).
aba