Open In App

Modify string by replacing all occurrences of given characters by specified replacing characters

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[][2], the task is to modify the given string S by replacing all occurrences of character P[i][0] with character P[i][1].

Examples:

Input: S = “aabbgg”, P[][2] = {{a, b}, {b, g}, {g, a}}
Output: bbggaa
Explanation:
Replace ‘a’ by ‘b’ in the original string. Now the string S modifies to “bbbbgg”.
Replace ‘b’ by ‘g’ in the original string. Now the string S modifies to “bbgggg”.
Replace ‘g’ by ‘a’ in the original string. Now the string S modifies to  “bbggaa”.

Input: S = “abc”, P[][2] = {{a, b}}
Output: bbc

Naive Approach: The simplest approach to solve the given problem is to create a copy of the original string S, and then for each pair (a, b) traverse the string, and if the character ‘a’ is found then replace it by character ‘b’ in the copy of the original string. After checking for all the pairs, print the modified string S.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to modify given string
// by replacement of characters
void replaceCharacters(
    string s, vector<vector<char> > p)
{
 
    // Store the length of the string
    // and the number of pairs
    int n = s.size(), k = p.size();
 
    // Create a copy of the string s
    string temp = s;
 
    // Traverse the pairs of characters
    for (int j = 0; j < k; j++) {
 
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Traverse the original string
        for (int i = 0; i < n; i++) {
 
            // If an occurrence of a is found
            if (s[i] == a) {
 
                // Replace with b
                temp[i] = b;
            }
        }
    }
 
    // Print the result
    cout << temp;
}
 
// Driver Code
int main()
{
    string S = "aabbgg";
    vector<vector<char> > P{ { 'a', 'b' },
                             { 'b', 'g' },
                             { 'g', 'a' } };
    replaceCharacters(S, P);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to modify given string
// by replacement of characters
static void replaceCharacters(String s, char p[][])
{
     
    // Store the length of the string
    // and the number of pairs
    int n = s.length(), k = p.length;
 
    // Create a copy of the string s
    char temp[] = s.toCharArray();
 
    // Traverse the pairs of characters
    for(int j = 0; j < k; j++)
    {
         
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Traverse the original string
        for(int i = 0; i < n; i++)
        {
 
            // If an occurrence of a is found
            if (s.charAt(i) == a)
            {
                 
                // Replace with b
                temp[i] = b;
            }
        }
    }
 
    // Print the result
    System.out.println(new String(temp));
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "aabbgg";
    char P[][] = { { 'a', 'b' },
                   { 'b', 'g' },
                   { 'g', 'a' } };
    replaceCharacters(S, P);
}
}
 
// This code is contributed by Kingash


Python3




# Python3 program for the above approach
 
# Function to modify given string
# by replacement of characters
def replaceCharacters(s, p):
     
    # Store the length of the string
    # and the number of pairs
    n = len(s)
    k = len(p)
 
    # Create a copy of the string s
    temp = s
 
    # Traverse the pairs of characters
    for j in range(k):
         
        # a -> Character to be replaced
        # b -> Replacing character
        a = p[j][0]
        b = p[j][1]
 
        # Traverse the original string
        for i in range(n):
             
            # If an occurrence of a is found
            if (s[i] == a):
                 
                # Replace with b
                temp = list(temp)
                temp[i] = b
                temp = ''.join(temp)
 
    # Print the result
    print(temp)
 
# Driver Code
if __name__ == '__main__':
     
    S = "aabbgg"
    P = [ [ 'a', 'b' ],
          [ 'b', 'g' ],
          [ 'g', 'a' ] ]
           
    replaceCharacters(S, P)
     
# This code is contributed by ipg2016107


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to modify given string
// by replacement of characters
static void replaceCharacters(string s, char[,] p)
{
     
    // Store the length of the string
    // and the number of pairs
    int n = s.Length, k = p.GetLength(0);
 
    // Create a copy of the string s
    char[] temp = s.ToCharArray();
 
    // Traverse the pairs of characters
    for(int j = 0; j < k; j++)
    {
         
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j, 0], b = p[j, 1];
 
        // Traverse the original string
        for(int i = 0; i < n; i++)
        {
 
            // If an occurrence of a is found
            if (s[i] == a)
            {
                 
                // Replace with b
                temp[i] = b;
            }
        }
    }
 
    // Print the result
    Console.WriteLine(new string(temp));
}
 
// Driver Code
public static void Main(string[] args)
{
    string S = "aabbgg";
    char [,]P = { { 'a', 'b' },
                  { 'b', 'g' },
                  { 'g', 'a' } };
                   
    replaceCharacters(S, P);
}
}
 
// This code is contributed by ukasp


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to modify given string
// by replacement of characters
function replaceCharacters(s, p)
{
     
    // Store the length of the string
    // and the number of pairs
    var n = s.length, k = p.length;
 
    // Create a copy of the string s
    var temp = s;
 
    // Traverse the pairs of characters
    for(j = 0; j < k; j++)
    {
         
        // a -> Character to be replaced
        // b -> Replacing character
        var a = p[j][0], b = p[j][1];
 
        // Traverse the original string
        for(i = 0; i < n; i++)
        {
             
            // If an occurrence of a is found
            if (s.charAt(i) == a)
            {
                 
                // Replace with b
                temp[i] = b;
                temp = temp.substring(0, i) + b +
                       temp.substring(i + 1, n);
            }
        }
    }
 
    // Print the result
    document.write((temp));
}
 
// Driver Code
var S = "aabbgg";
var P = [ [ 'a', 'b' ],
          [ 'b', 'g' ],
          [ 'g', 'a' ] ];
 
replaceCharacters(S, P);
 
// This code is contributed by umadevi9616
 
</script>


Output: 

bbggaa

 

Time Complexity: O(K * N)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized by using the two auxiliary arrays of size 26 to store the replacements in the array. Follow the steps below to solve the problem:

  • Initialize two arrays, arr[] and brr[] of size 26, and store the characters of the string, S in both the arrays.
  • Traverse the array of pairs P using the variable i and perform the following steps:
    • Initialize A as P[i][0] and B as P[i][1] denoting character A to be replaced by character B.
    • Iterate over the range [0, 25] using the variable j and if arr[j] is equal to A, then update brr[j] to B.
  • Traverse the given string S and for each S[i] update it to brr[S[i] – ‘a’].
  • After completing the above steps, print the modified string S.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to modify given
// string by replacing characters
void replaceCharacters(
    string s, vector<vector<char> > p)
{
    // Store the size of string
    // and the number of pairs
    int n = s.size(), k = p.size();
 
    // Initialize 2 character arrays
    char arr[26];
    char brr[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for (int i = 0; i < n; i++) {
        arr[s[i] - 'a'] = s[i];
        brr[s[i] - 'a'] = s[i];
    }
 
    // Traverse the array of pairs p
    for (int j = 0; j < k; j++) {
 
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Iterate over the range [0, 25]
        for (int i = 0; i < 26; i++) {
 
            // If it is equal to current
            // character, then replace it
            // in the array b
            if (arr[i] == a) {
                brr[i] = b;
            }
        }
    }
 
    // Print the array brr[]
    for (int i = 0; i < n; i++) {
        cout << brr[s[i] - 'a'];
    }
}
 
// Driver Code
int main()
{
    string S = "aabbgg";
    vector<vector<char> > P{ { 'a', 'b' },
                             { 'b', 'g' },
                             { 'g', 'a' } };
    replaceCharacters(S, P);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to modify given
// string by replacing characters
static void replaceCharacters(String s, char[][] p)
{
     
    // Store the size of string
    // and the number of pairs
    int n = s.length(), k = p.length;
 
    // Initialize 2 character arrays
    char[] arr = new char[26];
    char[] brr = new char[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for(int i = 0; i < n; i++)
    {
        arr[s.charAt(i) - 'a'] = s.charAt(i);
        brr[s.charAt(i) - 'a'] = s.charAt(i);
    }
 
    // Traverse the array of pairs p
    for(int j = 0; j < k; j++)
    {
         
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Iterate over the range [0, 25]
        for(int i = 0; i < 26; i++)
        {
             
            // If it is equal to current
            // character, then replace it
            // in the array b
            if (arr[i] == a)
            {
                brr[i] = b;
            }
        }
    }
 
    // Print the array brr[]
    for(int i = 0; i < n; i++)
    {
       System.out.print(brr[s.charAt(i) - 'a']);
    }
}
 
// Driver code
public static void main(String[] args)
{
    String S = "aabbgg";
    char[][] P = { { 'a', 'b' },
                   { 'b', 'g' },
                   { 'g', 'a' } };
                    
    replaceCharacters(S, P);
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program for the above approach
 
# Function to modify given
# string by replacing characters
def replaceCharacters(s, p):
     
    # Store the size of string
    # and the number of pairs
    n, k = len(s), len(p)
 
    # Initialize 2 character arrays
    arr = [0] * 26
    brr = [0] * 26
 
    # Traverse the string s
    # Update arrays arr[] and brr[]
    for i in range(n):
        arr[ord(s[i]) - ord('a')] = s[i]
        brr[ord(s[i]) - ord('a')] = s[i]
 
    # Traverse the array of pairs p
    for j in range(k):
 
        # a -> Character to be replaced
        # b -> Replacing character
        a, b = p[j][0], p[j][1]
 
        # Iterate over the range [0, 25]
        for i in range(26):
             
            # If it is equal to current
            # character, then replace it
            # in the array b
            if (arr[i] == a):
                brr[i] = b
 
    # Print the array brr[]
    for i in range(n):
        print(brr[ord(s[i]) - ord('a')], end = "")
 
# Driver Code
if __name__ == '__main__':
     
    S = "aabbgg"
    P = [ [ 'a', 'b' ],
          [ 'b', 'g' ],
          [ 'g', 'a' ] ]
           
    replaceCharacters(S, P)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
public class GFG{
 
  // Function to modify given
  // string by replacing characters
  static void replaceCharacters(string s, char[,] p)
  {
 
    // Store the size of string
    // and the number of pairs
    int n = s.Length, k = p.GetLength(0);
 
    // Initialize 2 character arrays
    char[] arr = new char[26];
    char[] brr = new char[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for(int i = 0; i < n; i++)
    {
      arr[s[i] - 'a'] = s[i];
      brr[s[i] - 'a'] = s[i];
    }
 
    // Traverse the array of pairs p
    for(int j = 0; j < k; j++)
    {
 
      // a -> Character to be replaced
      // b -> Replacing character
      char a = p[j,0], b = p[j,1];
 
      // Iterate over the range [0, 25]
      for(int i = 0; i < 26; i++)
      {
 
        // If it is equal to current
        // character, then replace it
        // in the array b
        if (arr[i] == a)
        {
          brr[i] = b;
        }
      }
    }
 
    // Print the array brr[]
    for(int i = 0; i < n; i++)
    {
      Console.Write(brr[s[i] - 'a']);
    }
  }
 
  // Driver code
 
  static public void Main ()
  {
 
    String S = "aabbgg";
    char[,] P = { { 'a', 'b' },
                 { 'b', 'g' },
                 { 'g', 'a' } };
 
    replaceCharacters(S, P);
 
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript




<script>
 
      // JavaScript program for the above approach
       
      // Function to modify given
      // string by replacing characters
      function replaceCharacters(s, p) {
        // Store the size of string
        // and the number of pairs
        var n = s.length,
          k = p.length;
 
        // Initialize 2 character arrays
        var arr = new Array(26).fill(0);
        var brr = new Array(26).fill(0);
 
        // Traverse the string s
        // Update arrays arr[] and brr[]
        for (var i = 0; i < n; i++) {
          arr[s[i].charCodeAt(0) - "a".charCodeAt(0)] = s[i];
          brr[s[i].charCodeAt(0) - "a".charCodeAt(0)] = s[i];
        }
 
        // Traverse the array of pairs p
        for (var j = 0; j < k; j++) {
          // a -> Character to be replaced
          // b -> Replacing character
          var a = p[j][0],
            b = p[j][1];
 
          // Iterate over the range [0, 25]
          for (var i = 0; i < 26; i++) {
            // If it is equal to current
            // character, then replace it
            // in the array b
            if (arr[i] === a) {
              brr[i] = b;
            }
          }
        }
 
        // Print the array brr[]
        for (var i = 0; i < n; i++) {
          document.write(brr[s[i].charCodeAt(0) -
          "a".charCodeAt(0)]);
        }
      }
 
      // Driver code
      var S = "aabbgg";
      var P = [
        ["a", "b"],
        ["b", "g"],
        ["g", "a"],
      ];
 
      replaceCharacters(S, P);
       
</script>


Output: 

bbggaa

 

Time Complexity: O(N + K)
Auxiliary Space: O(1)



Last Updated : 24 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads