In-place replace multiple occurrences of a pattern
Given a string and a pattern, replace multiple occurrences of a pattern by character ‘X’. The conversion should be in-place and the 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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool compare( char * str, char * pattern)
{
for ( int i = 0; pattern[i]; i++)
if (str[i] != pattern[i])
return false ;
return true ;
}
void replacePattern( char * str, char * pattern)
{
if (pattern == NULL)
return ;
int len = strlen (pattern);
if (len == 0)
return ;
int i = 0, j = 0;
int count;
while (str[j]) {
count = 0;
while (compare(str + j, pattern)) {
j = j + len;
count++;
}
if (count > 0)
str[i++] = 'X' ;
if (str[j])
str[i++] = str[j++];
}
str[i] = '\0' ;
}
int main()
{
char str[] = "GeeksforGeeks" ;
char pattern[] = "Geeks" ;
replacePattern(str, pattern);
cout << str;
return 0;
}
|
Java
public class ReplaceOccurrences
{
public static boolean compare(String str, String pattern)
{
for ( int i = 0 ; i<pattern.length(); i++)
if (str.charAt(i) != pattern.charAt(i))
return false ;
return true ;
}
public static String replacePattern(String str, String pattern)
{
if (pattern == "" )
return str;
int len = pattern.length();
if (len == 0 )
return str;
int i = 0 , j = 0 ;
int count;
while (j<str.length())
{
count = 0 ;
if (j + len <= str.length() && compare(str.substring(j,j+len), pattern))
{
j = j + len;
count++;
}
if (count > 0 )
{
String firstPart = str.substring( 0 ,i);
String lastPart = str.substring(i+ 1 );
str = firstPart + 'X' + lastPart;
i++;
}
if (j<str.length())
{
String firstPart = str.substring( 0 ,i);
String lastPart = str.substring(i+ 1 );
str = firstPart + str.charAt(j) + lastPart;
i++; j++;
}
}
String firstPart = str.substring( 0 ,i);
str = firstPart;
return str;
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
String pattern = "Geeks" ;
str = replacePattern(str, pattern);
System.out.println(str);
}
}
|
Python3
def compare( Str , pattern):
if ( len ( Str ) ! = len (pattern)):
return False
for i in range ( len (pattern)):
if ( Str [i] ! = pattern[i]):
return False
return True
def replacePattern( Str ,pattern):
if (pattern = = ""):
return
Len = len (pattern)
if ( Len = = 0 ):
return
i, j = 0 , 0
while (j < len ( Str )):
count = 0
while (compare( Str [j:j + Len ], pattern)):
j = j + Len
count + = 1
if (count > 0 ):
Str = Str [ 0 :i] + 'X' + Str [i + 1 :]
i + = 1
if (j< len ( Str )):
Str = Str [ 0 :i] + Str [j] + Str [i + 1 :]
i + = 1
j + = 1
Str = Str [ 0 :i]
return Str
Str = "GeeksforGeeks"
pattern = "Geeks"
Str = replacePattern( Str , pattern)
print ( Str )
|
C#
using System;
public class Program
{
static bool Compare( string str, string pattern)
{
for ( int i = 0; i < pattern.Length; i++)
if (str[i] != pattern[i])
return false ;
return true ;
}
static void ReplacePattern( char [] str, string pattern)
{
if (pattern == null )
return ;
int len = pattern.Length;
if (len == 0)
return ;
int i = 0, j = 0;
int count;
while (j < str.Length) {
count = 0;
while (j + len <= str.Length && Compare( new string (str, j, len), pattern)) {
j = j + len;
count++;
}
if (count > 0)
str[i++] = 'X' ;
if (j < str.Length)
str[i++] = str[j++];
}
str[i] = '\0' ;
}
public static void Main()
{
char [] str = "GeeksforGeeks" .ToCharArray();
string pattern = "Geeks" ;
ReplacePattern(str, pattern);
Console.WriteLine(str);
}
}
|
Javascript
<script>
function compare(str, pattern)
{
for (let i = 0; i<pattern.length; i++)
if (str[i] != pattern[i])
return false ;
return true ;
}
function replacePattern(str,pattern)
{
if (pattern == "" )
return ;
let len = pattern.length;
if (len == 0)
return ;
let i = 0, j = 0;
let count;
while (j<str.length) {
count = 0;
while (compare(str.substring(j,j+len), pattern)) {
j = j + len;
count++;
}
if (count > 0){
str = str.substring(0,i) + 'X' + str.substring(i+1,)
i++
}
if (j<str.length){
str = str.substring(0,i) + str[j] + str.substring(i+1,)
i++;j++
}
}
str = str.substring(0,i);
return str;
}
let str = "GeeksforGeeks" ;
let pattern = "Geeks" ;
str = replacePattern(str, pattern);
document.write(str, "</br>" );
</script>
|
Time complexity: O(n*m) where n is length of string and m is length of the pattern.
Auxiliary Space: O(1)
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
C++
#include <bits/stdc++.h>
using namespace std;
void replacePattern(string str, string pattern)
{
string::iterator it = str.begin();
while (it != str.end()) {
it = search(str.begin(), str.end(), pattern.begin(), pattern.end());
if (it != str.end()) {
str.erase(it, it + pattern.size());
str.insert(it, 'X' );
}
}
for ( int i = 0; i < str.size() - 1; i++) {
if (str[i] == 'X' && str[i + 1] == 'X' ) {
str.erase(str.begin() + i);
i--;
}
}
cout << str;
}
int main()
{
string str = "GeeksforGeeks" ;
string pattern = "Geeks" ;
replacePattern(str, pattern);
return 0;
}
|
Java
import java.io.*;
public class GFG {
static void replacePattern(StringBuilder str, String pattern) {
while (str.length() > 0 ) {
int index = str.indexOf(pattern);
if (index >= 0 ) {
str.delete(index, index + pattern.length());
str.insert(index, "X" );
} else {
break ;
}
}
for ( int i = 0 ; i < str.length() - 1 ; i++) {
if (str.charAt(i) == 'X' && str.charAt(i + 1 ) == 'X' ) {
str.deleteCharAt(i);
i--;
}
}
System.out.println(str);
}
public static void main(String[] args) {
StringBuilder str = new StringBuilder( "GeeksforGeeks" );
String pattern = "Geeks" ;
replacePattern(str, pattern);
}
}
|
Python3
import re
def replacePattern( str , pattern):
while (re.search(pattern, str )):
str = re.sub(pattern, 'X' , str , 1 )
i = 0
while (i < len ( str ) - 1 ):
if ( str [i] = = 'X' and str [i + 1 ] = = 'X' ):
str = str [:i] + str [i + 1 :]
else :
i + = 1
print ( str )
if __name__ = = "__main__" :
str = "GeeksforGeeks"
pattern = "Geeks"
replacePattern( str , pattern)
|
C#
using System;
using System.Linq;
class Gfg
{
static void replacePattern( ref string str, string pattern)
{
while (str.Length > 0)
{
int index = str.IndexOf(pattern);
if (index >= 0)
{
str = str.Remove(index, pattern.Length);
str = str.Insert(index, "X" );
}
else
{
break ;
}
}
for ( int i = 0; i < str.Length - 1; i++)
{
if (str[i] == 'X' && str[i + 1] == 'X' )
{
str = str.Remove(i, 1);
i--;
}
}
Console.WriteLine(str);
}
static void Main( string [] args)
{
string str = "GeeksforGeeks" ;
string pattern = "Geeks" ;
replacePattern( ref str, pattern);
}
}
|
Javascript
function replacePattern(str, pattern) {
while (str.search(pattern) !== -1) {
str = str.replace(pattern, 'X' );
}
let i = 0;
while (i < str.length - 1) {
if (str[i] === 'X' && str[i + 1] === 'X' ) {
str = str.substring(0, i) + str.substring(i + 1);
} else {
i++;
}
}
console.log(str);
}
const str = "GeeksforGeeks" ;
const pattern = /Geeks/g;
replacePattern(str, pattern);
|
Time Complexity: O(n*m)
Auxiliary Space: O(1)
Last Updated :
25 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...