Problem
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Algorithm
First save the words in a list and then reverse save the results in a string seperated with blanks.
Code
class Solution:
def reverseWords(self, s: str) -> str:
table = []
size = 0
buf = ""
for c in s:
if c == ' ':
if buf != "":
table.append(buf)
buf = ""
size += 1
else:
buf += c
if buf != "":
table.append(buf)
size += 1
ans = ""
for i in range(size-1, -1, -1):
if i < size-1:
ans += " "
ans += table[i]
return ans