Simple C++ solution


  • 0
    C

    A simple solution can be:

    class Solution {
    public:
        string reverseString(string s) {
             reverse(&s[0],&s[s.length()]);
            return s;
        }
    };
    

    But it seems that we are required to design a 'reverse' function, therefore we cant just use it directly.
    According to the the 'Submission Details' this can be a 6ms submission sample, based on the idea of original 'reverse' function, it can be designed as:

    class Solution {
    public:
        string reverseString(string s) {
             //reverse(&s[0],&s[s.length()]);
            int first=0, last;
            last = s.length();
            while((first!=last)&&(first!=--last)) {
                std::iter_swap(&s[first],&s[last]);
                ++first;
            }
            return s;
        }
    };
    

    this code will take longer time, but at least, it is kind of re-designed code.
    p.s. it will be quicker if we use s.length() rather than s.size()...


Log in to reply
 

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