[LeetCode] 344. Reverse String
Write a function that takes a string as input and returns the string reversed
Given s = "hello", return "olleh".
//solution.h
#ifndef SOLUTION_H
#define SOLUTION_H
#include<string>
using namespace std;
class Solution
{
public:
void reverseString_1(string& s);
void reverseString_2(string& s);
};
#endif
<span style="font-size:18px;">//solution.cpp
#include"solution.h"
void Solution::reverseString_1(string& s)
{
string temp = s;
for (int i(0); i<s.size(); i++)
{
s[i] = temp[s.size() - 1 - i];
}
}
void Solution::reverseString_2(string& s)
{
reverse(s.begin(), s.end());
}</span>
<span style="font-size:18px;">//main
#include<iostream>
#include<time.h>
#include"solution.h"
using namespace std;
int main()
{
cout << "please input a string: ";
string s;
cin >> s;
clock_t startTime, endTime;
Solution test;
startTime = clock();
test.reverseString_1(s);
endTime = clock();
cout << "The string after reverse with method 1: "<<s<<endl;
cout << "The time of method 1: " << endTime - startTime << "ms" << endl;
cout << endl;
startTime = clock();
test.reverseString_2(s);
endTime = clock();
cout << "The string after reverse with method 2: "<<s<<endl;
cout << "The time of method 2: " << endTime - startTime << "ms" << endl;
system("pause");
return 0;
}</span>