Given a string and a pattern, replace multiple occurrences of a pattern by character ‘X’. The conversion should be in-place and solution should replace multiple consecutive (and non-overlapping) occurrences of a pattern by a single ‘X’.
String – GeeksForGeeks Pattern – Geeks Output: XforX String – GeeksGeeks Pattern – Geeks Output: X String – aaaa Pattern – aa Output: X String – aaaaa Pattern – aa Output: Xa
The idea is to maintain two index i and j for in-place replacement. Index i always points to next character in the output string. Index j traverses the string and searches for one or more pattern match. If a match is found, we put character ‘X’ at index i and increment index i by 1 and index j by length of the pattern. Index i is increment only once if we find multiple consecutive occurrences of the pattern. If the pattern is not found, we copy current character at index j to index i and increment both i and j by 1. Since pattern length is always more than equal to 1 and replacement is only 1 character long, we would never overwrite unprocessed characters i.e j >= i is invariant.
The time complexity of above algorithm is O(n*m), where n is length of string and m is length of the pattern.
Implementation using STL
The idea of this implementation is to use the STL in-built functions to search for pattern string in main string and then erasing it from the main string
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Replace all occurrences of pi with 3.14 in a given string
- Replace all occurrences of a string with space
- Replace all occurrences of string AB with C without using extra space
- Recursive program to replace all occurrences of pi with 3.14 in a given string
- Count of occurrences of a "1(0+)1" pattern in a string
- Pattern Occurrences : Stack Implementation Java
- Occurrences of a pattern in binary representation of a number
- Inplace rotate square matrix by 90 degrees | Set 1
- Check if all occurrences of a character appear together
- Find k numbers with most occurrences in the given array
- Delete all occurrences of a given key in a linked list
- Group all occurrences of characters according to first appearance
- Count occurrences of a substring recursively
- Remove all occurrences of a character in a string
- Count occurrences of a word in string
Improved By : md1844