Replace two substrings (of a string) with each other
Last Updated :
15 Sep, 2022
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.
Examples:
Input: S = "aab", A = "aa", B = "bb"
Output: bbb
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"
Output: bbaabbaa
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:
C++
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
// Function to return the resultant string
string updateString(string S,
string A, string B)
{
int l = A.length();
// Iterate through all positions i
for (int i = 0; i + l <= S.length(); i++)
{
// Current sub-string of
// length = len(A) = len(B)
string curr = S.substr(i, i + l);
// If current sub-string gets
// equal to A or B
if (curr == A)
{
// Update S after replacing A
string new_string = "";
new_string += S.substr(0, i) + B +
S.substr(i + l, S.length());
S = new_string;
i += l - 1;
}
else if(curr == B)
{
// Update S after replacing B
string new_string = "";
new_string += S.substr(0, i) + A +
S.substr(i + l, S.length());
S = new_string;
i += l - 1;
}
else
{
//do nothing
}
}
// Return the updated string
return S;
}
// Driver code
int main()
{
string S = "aaxb";
string A = "aa";
string B = "bb";
cout << (updateString(S, A, B)) << endl;
}
// This code is contributed by
// Surendra_Gangwar
Java
// Java implementation of the approach
class GFG {
// Function to return the resultant string
static String updateString(String S, String A, String B)
{
int l = A.length();
// Iterate through all positions i
for (int i = 0; i + l <= S.length(); i++) {
// Current sub-string of length = len(A) = len(B)
String curr = S.substring(i, i + l);
// If current sub-string gets equal to A or B
if (curr.equals(A)) {
// Update S after replacing A
String new_string
= S.substring(0, i)
+ B + S.substring(i + l, S.length());
S = new_string;
i += l - 1;
}
else {
// Update S after replacing B
String new_string
= S.substring(0, i)
+ A + S.substring(i + l, S.length());
S = new_string;
i += l - 1;
}
}
// Return the updated string
return S;
}
// Driver code
public static void main(String[] args)
{
String S = "aab";
String A = "aa";
String B = "bb";
System.out.println(updateString(S, A, B));
}
}
Python3
# Python3 implementation of the approach
# Function to return the resultant string
def updateString(S, A, B):
l = len(A)
# Iterate through all positions i
i = 0
while i + l <= len(S):
# Current sub-string of
# length = len(A) = len(B)
curr = S[i:i+l]
# If current sub-string gets
# equal to A or B
if curr == A:
# Update S after replacing A
new_string = S[0:i] + B + S[i + l:len(S)]
S = new_string
i += l - 1
else:
# Update S after replacing B
new_string = S[0:i] + A + S[i + l:len(S)]
S = new_string
i += l - 1
i += 1
# Return the updated string
return S
# Driver code
if __name__ == "__main__":
S = "aab"
A = "aa"
B = "bb"
print(updateString(S, A, B))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the resultant string
static string updateString(string S, string A, string B)
{
int l = A.Length;
// Iterate through all positions i
for (int i = 0; i + l <= S.Length; i++)
{
// Current sub-string of length = len(A) = len(B)
string curr = S.Substring(i, l);
// If current sub-string gets equal to A or B
if (curr.Equals(A))
{
// Update S after replacing A
string new_string = S.Substring(0, i) +
B + S.Substring(i + l);
S = new_string;
i += l - 1;
}
else
{
// Update S after replacing B
string new_string = S.Substring(0, i) +
A + S.Substring(i + l);
S = new_string;
i += l - 1;
}
}
// Return the updated string
return S;
}
// Driver code
public static void Main()
{
string S = "aab";
string A = "aa";
string B = "bb";
Console.WriteLine(updateString(S, A, B));
}
}
// This code is contributed by Ryuga
PHP
<?php
// PHP implementation of the approach
// Function to return the resultant string
function updateString($S, $A, $B)
{
$l = strlen($A);
// Iterate through all positions i
for ($i = 0; $i + $l <= strlen($S); $i++)
{
// Current sub-string of length = len(A) = len(B)
$curr = substr($S, $i, $i + $l);
// If current sub-string gets equal to A or B
if (strcmp($curr, $A) == 0)
{
// Update S after replacing A
$new_string = substr($S, 0, $i) . $B .
substr($S, $i + $l, strlen($S));
$S = $new_string;
$i += $l - 1;
}
else
{
// Update S after replacing B
$new_string = substr($S, 0, $i) . $A .
substr($S, $i + $l, strlen($S));
$S = $new_string;
$i += $l - 1;
}
}
// Return the updated string
return $S;
}
// Driver code
$S = "aab";
$A = "aa";
$B = "bb";
echo(updateString($S, $A, $B));
// This code is contributed by Code_Mech.
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the resultant string
function updateString(S, A, B)
{
let l = A.length;
// Iterate through all positions i
for(let i = 0; i + l <= S.length; i++)
{
// Current sub-string of length = len(A) = len(B)
let curr = S.substring(i, i + l);
// If current sub-string gets equal to A or B
if (curr == A)
{
// Update S after replacing A
let new_string = S.substring(0, i) +
B + S.substring(i + l);
S = new_string;
i += l - 1;
}
else
{
// Update S after replacing B
let new_string = S.substring(0, i) +
A + S.substring(i + l);
S = new_string;
i += l - 1;
}
}
// Return the updated string
return S;
}
// Driver code
let S = "aab";
let A = "aa";
let B = "bb";
document.write(updateString(S, A, B));
// This code is contributed by mukesh07
</script>
Complexity Analysis:
- Time Complexity: O(n*n), as substr function is being used inside the loop
- Auxiliary Space: O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read