[
string
two pointers
]
BinarySearch 0171 Reverse Words
Problem statement
https://binarysearch.com/problems/Reverse-Words/
Solution
Equal to Leetcode 0186 Reverse Words in a String II.
Complexity
It is O(n)
for time. Space would have been O(1)
if it was array of characters, not strings.
Code
class Solution:
def solve(self, sentence):
s = [i for i in sentence]
def reverse(i, j):
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
beg, end = 0, 0
while end < len(s):
if s[end] == " ":
reverse(beg, end - 1)
beg, end = end + 1, end + 1
else:
end += 1
reverse(beg, end - 1)
reverse(0, len(s) - 1)
return "".join(s)