Leecode 0151. Reverse Words in a String
151. Reverse Words in a String
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:
1 | Input: s = "the sky is blue" |
Example 2:
1 | Input: s = " hello world " |
Example 3:
1 | Input: s = "a good example" |
题目分析
需要将字符串中的单词顺序反转,同时处理多余的空格(包括前导、尾随和单词间的多个空格),最终返回单词间仅用单个空格分隔的结果。
解题思路
- 首先处理字符串,去除多余的空格
- 反转整个字符串
- 再反转每个单词,得到最终结果
这种方法可以在 O (n) 时间复杂度内完成,且不需要额外的空间存储单词列表。
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.