Reverse Words In A String
MediumString · NVIDIA
Given a string s, return a new string containing the words of s in reverse order.
A *word* is a maximal run of non-space characters. s may have leading or trailing spaces and may have several spaces between two words.
- In the result, words are separated by exactly one space, with no leading or trailing spaces.
- The characters inside each word keep their original order; only the order of the words changes.
Example 1
- Input:
- s = " fly me to the moon "
- Output:
- "moon the to me fly"
- Explanation
- The words are
fly,me,to,the,moon. Reversed and joined with single spaces, the extra spaces at the ends and between words disappear.
Example 2
- Input:
- s = "R2 D2 C3PO"
- Output:
- "C3PO D2 R2"
- Explanation
- Digits are part of a word. Only the word order flips;
C3POitself is not reversed.
Example 3
- Input:
- s = " solo "
- Output:
- "solo"
- Explanation
- A single word stays as it is, with the surrounding spaces removed.
Constraints
1 <= s.length <= 10^4scontains English letters (upper and lower case), digits, and spaces' 'scontains at least one word