Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A or B, replace it, and then continue with the rest of the string.
For example, when matching A = “aa” with S = “aaa”, A[0, 1] will be given preference over A[1, 2].
Note that A and B will have the same length and A != B.
Input: S = “aab”, A = “aa”, B = “bb”
We match the first two characters with A and replacing it with B we get bbb.
Then we continue the algorithm starting at index 3 and we don’t find any more matches.
Input: S = “aabbaabb”, A = “aa”, B = “bb”
We replace all the occurrences of “aa” with “bb” and “bb” with “aa”, so the resultant string is “bbaabbaa”.
Approach: Go through every possible sub-string from S of length len(A). if any sub-string matches A or B then update the string as required and print the updated string in the end.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Number of substrings of a string
- Number of even substrings in a string of digits
- Different substrings in a string that start and end with given strings
- Number of substrings of one string present in other
- Sum of all substrings of a string representing a number | Set 1
- Count of substrings of a binary string containing K ones
- Lexicographical concatenation of all substrings of a string
- Program to print all substrings of a given string
- Split the string into substrings using delimiter
- Number of substrings divisible by 6 in a string of integers
- Lexicographically all Shortest Palindromic Substrings from a given string
- Reverse the substrings of the given String according to the given Array of indices
- Counting even decimal value substrings in a binary string
- Minimum changes to a string to make all substrings distinct
- Number of substrings with odd decimal value in a binary string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.