Wrap every continuous instance of given word with some given string
Given two string S1 and S2. The task is to wrap every instance of string S2 in string S1 with some string on either side.
Note: Here we will use underscore(_) for the wrapping part. It can be anything as per need, for example some HTML tag, white space, etc.
Input: S1 = “examwill be a examexam”, S2 = “exam”
Output: “_exam_will be a _examexam_”
String S2 is “exam“, so wrap occurrence of S2 with underscore. Since, last two occurrence overlaps(in string examexam), so merge both the occurrence and wrap by putting underscore to farther left and farther right of merged substring.
Input: str = “abcabcabcabc”, substr = “abc”
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Approach: The idea is to simply get the location of all instances of string S2 in S1 and add underscore at either end of the occurrence and if two or more instances of S2 overlaps then, add underscore at either end of the merged substring. Below are the steps:
- Get the location of all instances of the string S2 in the main string S1. For that traverse string S1 one character at a time and call substring-matching function, find().
- Create a 2D array of locations(say arr), where each subarray holds the starting and ending indices of a specific instance of the string S2 in the string S1.
- Merge the overlapping starting and ending index intervals stored in arr.
- After the above steps all the overlapping indexes are merged. Now traverse the given string and intervals at the same time and create a new string by wrapping underscores.
- Print the new string after the above step.
Below is the implementation of the above approach:
_exam_will be a _examexam_
Time Complexity: O(N * M), where N and M is the length of the string S1 and S2 respectively.
Auxiliary Space: O(N), where N is the length of string S1