LeetCode 151
151. Reverse Words in a String
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.
Solution
We can use the python split function to create a list containing each word and removing all spaces. Originally, I had used s.split(" ")
, but this created an issue of multiple spaces being detected as their own word. Once we have the list of words we can use the reversed function to reverse the list and then join all words with a space between.
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))