[
string
two pointers
]
BinarySearch 0172 Reverse Words Sequel
Problem statement
https://binarysearch.com/problems/Reverse-Words-Sequel/
Solution
First, create copy, where we replace all delimiters to !
and then split our copy to create words. Notice that some of them can be empty. Then use two pointers approach to reverse the order of words (because we can have empty words, we want to skip them). Also keep array of delimeters. In the end combine reversed words and delimeters.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def solve(self, s, d):
s2 = "".join([x if x not in d else "!" for x in s])
dels = [x for x in s if x in d]
words = s2.split("!")
beg, end = 0, len(words) - 1
while beg < end:
while words[beg] == "": beg += 1
while words[end] == "": end -= 1
words[beg], words[end] = words[end], words[beg]
beg += 1
end -= 1
ans = [words[0]]
for i in range(1, len(words)):
ans += [dels[i-1]]
ans += [words[i]]
return "".join(ans)