C++:反转字符串

class Solution {
public:
    string reverseString(string s) 
    {
        if(s[0] == NULL)//空返回
            return s;
        int begin = 0;//设置头指针
        int end = s.size() - 1;//设置尾指针
        while(begin < end)
        {
            swap(s[begin], s[end]);
            begin++;
            end--;
        }
        return s;
    }
};

思路:设置头尾两个指针,两个指针交换,然后头++,尾–,两个指针交替或者相等的时候跳出循环,返回第一位数的下标。

猜你喜欢

转载自blog.csdn.net/l477918269/article/details/86564232