557. 反转字符串中的单词 III
557. 反转字符串中的单词 III
题目
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Constraints:
1 <= s.length <= 5 * 10^4
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.- There is at least one word in
s
. - All the words in
s
are separated by a single space.
题目大意
给定一个字符串 s
,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
解题思路
- 先将字符串按空格分割为子串数组;
- 依次反转每一个子串,反转子串的方法同 第 344 题;
- 再将反转后的单词连接起来;
复杂度分析
- 时间复杂度:
O(n)
,反转字符串需要遍历一半的字符。 - 空间复杂度:
O(n)
,用于保存字符串被split
后的数组。
代码
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function (s) {
return s
.split(' ')
.map((i) => reverse(i))
.join(' ');
};
var reverse = function (s) {
let arr = s.split(''),
n = s.length;
for (let i = 0; i < n / 2; i++) {
[arr[i], arr[n - 1 - i]] = [arr[n - 1 - i], arr[i]];
}
return arr.join('');
};
相关题目
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
541 | 反转字符串 II | 双指针 字符串 | 🟢 | 🀄️ 🔗 |