Reverse Words in a String
medium
strings
Given a string s, reverse the order of its words. A word is a maximal sequence of non-space characters. When you build the answer, remove any leading or trailing spaces and collapse every run of multiple spaces between words into a single space in the returned string. See the examples and constraints below, then consider the follow-up about solving it in-place.
Input / output
- Input:
s: string - Output:
string
Constraints
1 <= s.length <= 10^4scontains English letters, digits, punctuation, and spaces.- A word is any maximal contiguous block of non-space characters.
Follow-up
Could you solve it in-place with O(1) extra space in a language that supports mutable fixed-size character arrays?
Examples
Example 1
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2
Input: s = " hello world "
Output: "world hello"