Given a string S consisting of N characters and an array M[] of pairs of characters such that any character M[i][0] may be changed with the character M[i][1] within the string S, the duty is to generate all of the doable strings shaped by changing some characters of the string with their respective symbols within the array M[].
Examples:
Enter: S = “aBc”, M = {‘a’ : ‘$’, ‘B’ : ‘#’, ‘c’ : ‘^’}
Output:
aBc
aB^
a#c
a#^
$Bc
$B^
$#c
$#^Enter: S = “a”, M={‘a’ : ‘$’}
Output:
a
$
Strategy: The given downside may be solved by utilizing Backtracking to generate all doable strings by changing every character with the mapped character within the array M[]. Comply with the steps beneath to resolve the issue:
- Retailer all of the pairs of the mapped characters within the array M[] in a map, say Map.
- Outline a recursive perform say generateLetters(S, P), the place S is the modified string and P is the index of the present character:
- Test for the bottom case i.e., if index P equals to the N then print the string S and return.
- Don’t change the present character and recursively name for the perform, generateLetters(S, P + 1).
- Now, change the character, S[P] with the respective image within the map M and name for the perform, generateLetters(S, P+1).
- After finishing the above steps, name for the perform generateLetters(S, 0) to print all doable strings.
Under is the implementation of the above method:
C++
|
aBc aB^ a#c a#^ $Bc $B^ $#c $#^
Time Complexity: O(N*2N)
Auxiliary House: O(1)
Consideration reader! Don’t cease studying now. Pay money for all of the vital DSA ideas with the DSA Self Paced Course at a student-friendly value and change into business prepared. To finish your preparation from studying a language to DS Algo and plenty of extra, please refer Full Interview Preparation Course.
In case you want to attend dwell courses with specialists, please refer DSA Stay Lessons for Working Professionals and Aggressive Programming Stay for College students.