![]() |
Given a string W, change the string in such a way that it does not contain any of the “forbidden” strings S1 to Sn as one of its substrings. The rules that govern this change are as follows:
Examples: Input : n = 3 s1 = "etr" s2 = "ed" s3 = "ied" W = "PEtrUnited" letter = "d" Output : PDddUnitda Input : n = 1 s1 = "PetrsDreamOh" W = "PetrsDreamOh" letter = h Output : HhhhhHhhhhHa Explanation: Example 1: First character P does not belong to any of the substrings therefore it is not changed. The next three characters form the substring “etr” and are changed to “Ddd”. The next four characters do not belong to any of the forbidden substrings and remain unchanged. The next two characters form the substring “ed” and are changed to “da” since d is The last character itself, it is replaced with another character ‘a’ such that the string is lexicographically the smallest. Notice: “Etr” = “etr” and the changed substring “Ddd” has first character as ‘D’ since first letter of “Etr” is in uppercase. Example 2: Since the entire string is a forbidden string, it is replaced with letter ‘h’ from first to second last character according to the case. The last character is ‘h’ therefore it is replaced with letter ‘a’ such that the string is lexicographically the smallest. Approach: Check for every character of the string W, if it is the beginning of the any of the substrings or not. Use another array to keep record of the characters of W that are part of the forbidden strings and needs to be changed.
The first and second condition will also be used when W[i] is an uppercase character. Below is the implementation of the above approach: C++
Java
Python3
C#
Javascript
Output
PDddUnitda Time Complexity: O(n) |
Reffered: https://www.geeksforgeeks.org
Competitive Programming |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |