344. 反转字符串
344. 反转字符串
题目
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:
1 <= s.length <= 10^5
s[i]
is a printable ascii character.
题目大意
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 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 | 双指针 字符串 |