Skip to content

Latest commit

 

History

History
87 lines (66 loc) · 2.55 KB

0557.md

File metadata and controls

87 lines (66 loc) · 2.55 KB
title description keywords
557. 反转字符串中的单词 III
LeetCode 557. 反转字符串中的单词 III题解,Reverse Words in a String III,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
557. 反转字符串中的单词 III
反转字符串中的单词 III
Reverse Words in a String III
解题思路
双指针
字符串

557. 反转字符串中的单词 III

🟢 Easy  🔖  双指针 字符串  🔗 力扣 LeetCode

题目

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 ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

解题思路

  1. 先将字符串按空格分割为子串数组;
  2. 依次反转每一个子串,反转子串的方法同 第 344 题
  3. 再将反转后的单词连接起来;

复杂度分析

  • 时间复杂度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 [✓] 双指针 字符串 🟢 🀄️ 🔗