Skip to content

Latest commit

 

History

History
80 lines (58 loc) · 2.56 KB

0344.md

File metadata and controls

80 lines (58 loc) · 2.56 KB
title description keywords
344. 反转字符串
LeetCode 344. 反转字符串题解,Reverse String,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
344. 反转字符串
反转字符串
Reverse String
解题思路
双指针
字符串

344. 反转字符串

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

题目

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in- place with O(1) extra memory.

Example 1:

Input: s = ["h","e","l","l","o"]

Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]

Output: ["h","a","n","n","a","H"]

Constraints:

题目大意

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

解题思路

可以将数组的首位元素一一交换即可。

复杂度分析

  • 时间复杂度O(n),其中 n = s.length / 2,要遍历一半的数组。
  • 空间复杂度O(1)

代码

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {
	const n = s.length;
	for (let i = 0; i < n / 2; i++) {
		[s[i], s[n - 1 - i]] = [s[n - 1 - i], s[i]];
	}
};

相关题目

题号 标题 题解 标签 难度 力扣
345 反转字符串中的元音字母 [✓] 双指针 字符串 🟢 🀄️ 🔗
541 反转字符串 II [✓] 双指针 字符串 🟢 🀄️ 🔗