跳至主要內容

344. 反转字符串


344. 反转字符串open in new window

🟢   🔖  双指针 字符串  🔗 力扣open in new window LeetCodeopen in new window

题目

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- placeopen in new window 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反转字符串中的元音字母open in new window[✓]双指针 字符串
541反转字符串 IIopen in new window双指针 字符串