Simple C++ solution


  • 31
    class Solution {
    public:
        string reverseString(string s) {
            int i = 0, j = s.size() - 1;
            while(i < j){
                swap(s[i++], s[j--]); 
            }
            
            return s;
        }
    };

  • 0
    Y
    class Solution {
    public:
        string reverseString(string s) {
            for(int i=0,j=s.length()-1; i<j; ++i,--j)
                swap(s[i], s[j]);
            return s;
        }
    };
    

  • 2

    Hi, if s is empty, j would be a big number in some system.

    s.size() is unsigned int and 0 - 1 = -1 in some system. But 0 - 1 = Max Unsigned int in other.


  • 1
    P

    Another solution:

    class Solution {
    public:
        string reverseString(string s) {
            int n = s.size();
            for(int i = 0; i < n/2; i++) {
                swap(s[i], s[n - 1 - i]);
            }
            return s;
        }
    };
    

  • 0
    K

    Same solution in python,

    class Solution(object):
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            i, j =0, len(s)-1
            ls = list(s)
            while i <j:
                ls[i], ls[j] = ls[j], ls[i]
                i+=1
                j-=1
            return "".join(str(x) for x in ls)
    

  • 0
    class Solution {
    public:
        string reverseString(string s) {
            reverse(s.begin() , s.end() ); 
            return s;
        }
    };
    

  • 0
    T

    @Ximin.Z class Solution {
    public:
    string reverseString(string s) {
    int l=0,r=s.length()-1;
    while(l<r)
    {
    s[l]^=s[r];
    s[r]^=s[l];
    s[l]^=s[r];
    l++;r--;
    }
    return s;
    }
    };


  • 0
    H
    class Solution {
    public:
        string reverseString(string s) {
            return { s.rbegin(), s.rend() };
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.