344. Reverse String

来源:互联网 发布:nginx代理apache 400 编辑:程序博客网 时间:2024/05/16 11:02

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

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

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems
解法1:

class Solution {public:    string reverseString(string s) {    int left = 0, right = s.size()-1;    while (left<right)    {        swap(s[left++] , s[right--]);//运用交换函数,逐一交换位置    }    return s;    }};

解法2:

class Solution {public:    string reverseString(string s) {        int left = 0, right = s.size() - 1;        while (left < right) {//与上面的一个道理,只是是自己写的swap函数            char t = s[left];            s[left++] = s[right];            s[right--] = t;        }        return s;    }};
0 0
原创粉丝点击