151. Reverse Words in a String
Solution:
- first added the words to a list and joined up the list.
- the code below is similar except I looped through the string backwards and just appended to the ret string. technically I think this is the same as looping forward and just prepending to the ret string.. but oh well.
class Solution:
def reverseWords(self, s: str) -> str:
i = len(s) - 1
ret = ""
first = True
while i >= 0:
while i >= 0 and s[i] == ' ':
i -= 1
j = i - 1
while j >= 0 and s[j] != ' ':
j -= 1
if s[j+1:i+1]:
if first:
first = False
else:
ret += ' '
ret += s[j+1:i+1]
i = j - 1
return ret