跳至主要內容

344. Reverse String


344. Reverse Stringopen 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:

题目大意

题目要求我们反转一个字符串。

解题思路

这一题的解题思路是用 2 个指针,指针对撞的思路,来不断交换首尾元素,即可。

代码

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {
  let front = 0;
  let end = s.length - 1;
  let temp;
  while (front < end) {
    temp = s[front];
    s[front] = s[end];
    s[end] = temp;
    front++;
    end--;
  }
};

相关题目

相关题目
- [345. 反转字符串中的元音字母](./0345.md)
- [541. 反转字符串 II](https://leetcode.com/problems/reverse-string-ii)