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:

Recursively:

Last updated

Was this helpful?