Tuesday, 19 Oct 2021

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

Modify string by replacing all occurrences of given characters by specified replacing characters Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[], the task is to modify the given string S by replacing all occurrences of character P[i] with character P[i].Examples:Input: S = “aabbgg”, P[] = {{a, b}, {b, g}, {g, a}}Output: bbggaaExplanation: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[] = {{a, b}}Output: bbcNaive 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++#include using namespace std;void replaceCharacters(    string s, vector p){            int n = s.size(), k = p.size();        string temp = s;        for (int j = 0; j < k; j++) {                        char a = p[j], b = p[j];                for (int i = 0; i < n; i++) {                        if (s[i] == a) {                                temp[i] = b;            }        }    }        cout