151. Reverse Words in a String
On This Page
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.
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
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.
An efficient approach would be to:
- Split the string into individual words using the
splitmethod. This will take care of multiple spaces.
- Reverse the order of words using slicing.
- Join the words in reversed order using the
- Use the
splitmethod to split
sinto individual words. This will return a list of words.
- Reverse the order of words in the list using slicing.
- Use the
joinmethod to concatenate the words in reversed order and return the result.
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])