Space
Open
From Fieldwork
Scales
Archive
If we're allowed to just use the stuff...
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1])If we have to do things manually...
class Solution:
def reverseWords(self, s: str) -> str:
left, right = 0, len(s) - 1
# Trim edges first to reduce loop iterations
while left <= right and s[left] == ' ':
left += 1
while left <= right and s[right] == ' ':
right -= 1
queue = deque()
word = []
while left <= right:
if s[left] != ' ':
# Build the current word char by char
word.append(s[left])
elif word:
# We hit a space! Push the complete word to the FRONT
queue.appendleft("".join(word))
word = []
left += 1
# Don't forget the last word (since the string doesn't end with a space)
if word:
queue.appendleft("".join(word))
return " ".join(queue)
Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode