151. Reverse Words in a String
On This Page
Problem Statement
The problem is about reversing the order of words in a given string s
. Each word in s
is defined as a sequence of non-space characters and the words are separated by at least one space. You are expected to return a string with the words in reversed order and separated by a single space. It is important to note that s
may contain leading or trailing spaces or multiple spaces between two words, but the returned string should not contain any extra spaces.
Naive Solution
A naive solution could be to split the input string into individual words and then reverse the order of these words. However, this would require extra space to store the words and does not take care of multiple, leading, or trailing spaces.
Hints & Tips
Python’s built-in string methods split
and join
can be very helpful in this problem. The split
method can be used to split the string into individual words, and it also takes care of multiple spaces. The join
method can be used to concatenate the words in reverse order.
Approach
An efficient approach would be to:
- Split the string into individual words using the
split
method. This will take care of multiple spaces. - Reverse the order of words using slicing.
- Join the words in reversed order using the
join
method.
Steps
- Use the
split
method to splits
into individual words. This will return a list of words. - Reverse the order of words in the list using slicing.
- Use the
join
method to concatenate the words in reversed order and return the result.
Python Solution
class Solution:
def reverseWords(self, s: str) -> str:
words = s.split()
words.reverse()
return ' '.join(words)
Or even shorter:
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1])