Introduction
This blog will discuss the approach to generate all possible strings formed by replacing letters with given respective symbols. Before jumping on the approach to generate all possible strings formed by replacing letters with given respective symbols, let’s first understand the problem,
Problem Statement
According to the problem statement, we need to find all the characters provided in the set, and after that, we need to replace those characters with the respective symbols provided to us, and then we need to print all the possible strings.
Sample Example
Input:
String: code
M:- { ‘c’ : ‘^’ , ‘o’ : ‘$’ , ‘d’ : ‘#’ , ‘e’ : ‘&’ }
where M represents the symbol corresponding to each of the letter in given string i.e M[i][0] can be replaced with M[i][1], 0 ≤ i ≤ 3
Output:
- code
- cod&
- co#e
- co#&
- c$de
- c$d&
- c$#e
- c$#&
- ^ode
- ^od&
- ^o#e
- ^o#&
- ^$de
- ^$d&
- ^$#&
- ^$#e
Approach
This approach considers replacing each character with their desired symbol and then generating all the possible strings using backtracking.
Steps of algorithm
Step 1. Call a ‘getResult’ function, which takes three parameters, a string input, the current index of the string, and the unordered map.
Step 2. In this function, check for the base case, in which if the value of the current index and the size of the string is equal, then we need to print that string.
Step 3. If base is not triggered then, store the character at ‘lth’ index of ‘input’ string and then replace the character according to its mapping in the unordered map and then call the ‘getResult’ function by passing the next index of the current index and then after this call, replace that character at ‘lth’ index with the already stored character.
Step 4. Now call the ‘getResult’ function by passing the next index of the current index ‘l’ with the character at ‘lth’ index of string ‘input’ already replaced with the original character