-
Notifications
You must be signed in to change notification settings - Fork 0
/
114.py
25 lines (19 loc) · 797 Bytes
/
114.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# This problem was asked by Facebook.
# Given a string and a set of delimiters, reverse the words in the string while
# maintaining the relative order of the delimiters. For example, given "hello/world:here", return "here/world:hello"
# Follow-up: Does your solution work for the following cases: "hello/world:here/",
# "hello//world:here"
####
import re
def reverse_words(arr, delim):
re_delimiter = '|'.join(delim)
words = re.split(re_delimiter, arr)
seq_delims = re.findall(re_delimiter, arr)
words = words[::-1]
final_string = words[0]
for word, delim in zip(words[1:], seq_delims):
final_string += delim + word
return final_string
####
print(reverse_words("hello//world:here", ['/',':']))
print(reverse_words("hello/world:here/", ['/',':']))