151. Reverse Words in a String ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: String
, Two Pointers
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.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input:
Output:
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
The input string s
contains only printable ASCII characters.
s
does not contain any leading or trailing spaces.
The words in s
will be separated by a single space.
To solve this problem, we can split the string into words, remove any extra spaces, and reverse the list of words. Finally, we join them back into a string with a single space separating the words.
O(n): The time complexity is linear, where n
is the length of the input string.
O(n): The space complexity is also linear, as we are storing the reversed words in a new string.
You can find the full solution .