[leetcode] Reverse String 翻转字符串
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
这道题没什么难度,直接从两头往中间走,同时交换两边的字符即可,参见代码如下:
我的解法:
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
class StringSolution {
public:
string reverseString(string s) {
string reversed(s);
int index = 0;
for (int i = s.length()-1; i >= 0; i--)
{
reversed[index++] = s[i];
}
return reversed;
}
};
void main()
{
string str = "wuzhigang";
StringSolution ss;
string results=ss.reverseString(str);
cout << str.size() << endl;
for (auto a : results)
{
cout << a ;
}
system("pause");
}
解法一:
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;
}
};