The Wayback Machine - https://web.archive.org/web/20210414112751/https://www.geeksforgeeks.org/modify-string-by-replacing-all-occurrences-of-given-characters-by-specified-replacing-characters/
Skip to content
Related Articles

Related Articles

Modify string by replacing all occurrences of given characters by specified replacing characters
  • Last Updated : 14 Apr, 2021
GeeksforGeeks - Summer Carnival Banner

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;
}
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;
}
Output:
bbggaa

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :