151. 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:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 10^4
s
contains English letters (upper-case and lower-case), digits, and spaces' '
.- There is at least one word in
s
.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1)
extra space?
题目大意
给定一个字符串,逐个翻转字符串中的每个单词。
说明:
- 无空格字符构成一个单词。
- 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
- 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
请尝试使用 O(1)
额外空间复杂度的 原地 解法。
解题思路
常规的方式是把 s
按空格 split
成若干单词,然后 reverse
这些单词的顺序,最后把这些单词 join
成句子。但这种方式使用了额外的空间,并不是「原地反转」单词。
正确的做法是,先将整个字符串 s
反转,然后将每个单词分别反转,这样,就实现了原地反转所有单词。
原始字符串: "hello world!"
反转整个字符串: "!dlrow olleh"
分别反转每个单词: "world! hello"
不过由于 JS
中字符串是不可变的,字符串方法不会改变原有字符串的内容,而是返回一个新字符串,所以在 JS
中并不是真正的原地反转。
代码
/**
* @param {string} s
* @return {string}
*/
// 非原地反转
var reverseWords = function (s) {
return s
.split(" ")
.reverse()
.filter((i) => i != "")
.join(" ");
};
相关题目
- [🔒 Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii)