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:
- Number of substrings of a string
- Lexicographical concatenation of all substrings of a string
- Count of substrings of a binary string containing K ones
- Split the string into substrings using delimiter
- Program to print all substrings of a given string
- Number of substrings of one string present in other
- Different substrings in a string that start and end with given strings
- Number of even substrings in a string of digits
- Sum of all substrings of a string representing a number | Set 1
- Number of substrings divisible by 6 in a string of integers
- Number of substrings with odd decimal value in a binary string
- Counting even decimal value substrings in a binary string
- Minimum changes to a string to make all substrings distinct
- Replace all occurrences of pi with 3.14 in a given string
- Replace a character c1 with c2 and c2 with c1 in a string S
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.