Skip to main content

344, Reverse String

MikeLess than 1 minutestringeasystringtwo pointers

I Problem

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

Related Topics

  • Two Pointers
  • String

II Solution

Approach 1: Two Pointers

pub fn reverse_string(s: &mut Vec<char>) {
    let mut l = 0;
    let mut r = s.len() - 1;

    while l < r {
        s.swap(l, r);
        l += 1;
        r -= 1;
    }
}