Problem
Problem page: https://leetcode.com/problems/reverse-words-in-a-string/
Topics: String
Difficulty: Medium
Similar problems: (M) Reverse Words in a String II
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word.- Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.- How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Analysis
Reverse the order of the words in a sentence. Note that you also need to remove any leading or trailing whitespace and leave just one space between words.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-reverse-words-in-a-string/
