-
Notifications
You must be signed in to change notification settings - Fork 96
/
114.py
83 lines (71 loc) · 2.06 KB
/
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Problem:
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"
"""
from typing import Set
def rev_words(string: str, delimiters: Set[str]) -> str:
if len(string) == 0:
return string
words = []
delims = []
flag_beg = string[0] in delimiters
flag_delim = False
curr_str = ""
# generating the words and delimiters
for char in string:
if char in delimiters:
if flag_delim:
curr_str += char
else:
if curr_str:
words.append(curr_str)
curr_str = char
flag_delim = True
else:
if flag_delim:
flag_delim = False
delims.append(curr_str)
curr_str = char
else:
curr_str += char
# check if last character is a delimiter
if flag_delim:
delims.append(curr_str)
else:
words.append(curr_str)
words = words[::-1]
words.append("")
delims.append("")
len_words = len(words)
len_delims = len(delims)
i, j = 0, 0
reversed_string = ""
# generating the reversed string
if flag_beg:
j = 1
reversed_string += delims[0]
while i < len_words or j < len_delims:
try:
reversed_string += words[i]
reversed_string += delims[j]
i += 1
j += 1
except IndexError:
break
return reversed_string
if __name__ == "__main__":
print(rev_words("hello/world:here", {":", "/"}))
print(rev_words("here/world:hello", {":", "/"}))
print(rev_words("hello/world:here/", {":", "/"}))
print(rev_words("hello//world:here", {":", "/"}))
print(rev_words("hello", {":", "/"}))
print(rev_words("//:", {":", "/"}))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""