Suppose we have a string and a set of delimiters, we have to reverse the words in the string while the relative ordering of the delimiters should not be changed.
So, if the input is like s = "Computer/Network:Internet|tutorialspoint" delims = ["/", ":", '|'], then the output will be tutorialspoint/Internet:Network|Computer
To solve this, we will follow these steps:
words := a new list
ans := blank string
temp := a map where
Separate the words except the delimiter characters and insert them into words array
separate words when the character is in delimiter then add them into ans,
otherwise read word from words array reversely and add into ans
return ans
Let us see the following implementation to get better understanding:
Example
from itertools import groupby class Solution: def solve(self, sentence, delimiters): words = [] ans = "" for k, g in groupby(sentence, lambda x: x in delimiters): if not k: words.append("".join(g)) for k, g in groupby(sentence, lambda x: x in delimiters): if k: ans += "".join(g) else: ans += words.pop() return ans ob = Solution() s = "Computer/Network:Internet|tutorialspoint" delims = ["/", ":", '|'] print(ob.solve(s, delims))
Input
"Computer/Network:Internet|tutorialspoint", ["/", ":", '|']
Output
tutorialspoint/Internet:Network|Computer