1.问题描述
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
来自 https://leetcode.com/problems/reverse-string/description/
2.题目分析
对字符串经行反转,可以调用string类的reverse成员函数,也可以自己写。
3.c++代码
//我的c++代码:(beats 97%)
string reverseString(string& s)
{
for (int i = 0, j= s.length()-1; i < j; i++,j--)
{
char c = s[j];
s[j] = s[i];
s[i] = c;
}
return s;
}
4.string类的reverse函数
//algorithm中的定义
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
while ((first!=last)&&(first!=--last)) {
std::iter_swap (first,last);
++first;
}
}
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
string a;
while (cin >> a)
{
string b;
reverse(a.begin(), a.end());
cout << a << endl;
b = a;
cout << b << endl;
}
return 0;
}