344 Reverse String

Write a function that takes a string as input and returns the string reversed.

Example: Given s = "hello", return "olleh".

string reverseString(string &s) {
    const size_t size = s.length();
    const size_t size_half = s.length() / 2;
    int front = 0;
    int end = size - 1;
    if (size % 2 != 0) {
        for (int i = 0; i < size_half + 1; i++) {
            char temp = s[front];
            s[front++] = s[end];
            s[end--] = temp;
        }
    }
    else {
        for (int i = 0; i < size_half; i++) {
            char temp = s[front];
            s[front++] = s[end];
            s[end--] = temp;
        }
    }
    return s;
}

Simply:

string reverseString(string s) {
    int i = 0, j = s.size() - 1;
    while(i < j){
        swap(s[i++], s[j--]); 
    }

    return s;
}

Recursively:

void reverse(string &s, int start, int end)
{
    if (start < end)
    {
        char temp = s[start];
        s[start] = s[end];
        s[end] = temp;
    }
    start++; end--;
}

void reverse(string &s)
{
    reverse(s, 0, s.size() - 1);
}

Last updated