假设我们有一个字符串和一组定界符,我们必须反转字符串中的单词,而定界符的相对顺序不应更改。
因此,如果输入类似于s =“ Computer / Network:Internet | nhooo” delims = [“ /”,“:”,'|'],则输出将为nhooo / Internet:Network | Computer
为了解决这个问题,我们将按照以下步骤操作:
单词:=一个新列表
ans:=空字符串
temp:=map
分隔词(分隔符除外)并将其插入单词数组
当字符位于定界符中时,将其分开,然后将其添加到ans中,
否则从单词数组中反向读取单词并添加到ans中
返回ans
让我们看下面的实现以更好地理解:
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|nhooo" delims = ["/", ":", '|'] print(ob.solve(s, delims))
"Computer/Network:Internet|nhooo", ["/", ":", '|']
输出结果
nhooo/Internet:Network|Computer