[LeetCode] Reverse String 翻转字符串

 

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

Example:
Given s = “hello”, return “olleh”.

 

这道题没什么难度,直接从两头往中间走,同时交换两边的字符即可,参见代码如下:

 

解法一:

class Solution {
public:
    string reverseString(string s) {
        int left = 0, right = s.size() - 1;
        while (left < right) {
            char t = s[left];
            s[left++] = s[right];
            s[right--] = t;
        }
        return s;
    }
};

 

我们也可以用swap函数来帮助我们翻转:

 

解法二:

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

 

类似题目:

Reverse Words in a String II

Reverse Words in a String

 

    原文作者:Grandyang
    原文地址: http://www.cnblogs.com/grandyang/p/5420836.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞