Categories:

Tags:



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-place with O(1) extra memory.

Constraints

  • 1 <= s.length <= 105
  • s[i] is a printable ascii character.

Solution

The problem Reverse String can be solved by replacing characters of a given string from each end.

Implementation

class Solution
{
  public:
    void reverseString(vector<char> &s)
    {
        int len = s.size();
        for (int i = 0; i < len / 2; i++)
            swap(s[i], s[len - 1 - i]);
    }
};