[
string
two pointers
]
Leetcode 0186 Reverse Words in a String II
Problem statement
https://leetcode.com/problems/reverse-words-in-a-string-ii/
Solution
Just special case of problem 0151: what we need to do here is to reverse each word, using two pointers technique and then reverse whole string.
Complexity
Time complexity is $O(n)$, space complexity is $O(1)$, because we do everything in place.
Code
class Solution:
def reverseWords(self, s):
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)