1)题目
反转字符串
要求:
写一个方法,接受给定字符串作为输入,返回将这个字符串逐个字符翻转后的新字符串。
样例
输入:“hello”
输出:“olleh”
样例 2:
输入:“hello world”
输出:“dlrow olleh”
2)思路
从后往前遍历字符串,将每一个字符串起来
3)代码
两种方法:
//头文件
class Solution {
public:
/**
* @param s: a string
* @return: return a string
*/
string reverseString(string &s)
{
string str;
for (int i = s.size()-1; i >= 0; i--)
{
str += s[i];
}
return str;
};
};
//主函数
#include "pch.h"
#include <iostream>
using namespace std;
#include <string>
#include "1283.h"
class Solution;
Solution function;
int main()
{
//string str(":!Py\"2'e6:fe2O`i,z19LU7 2DrZQ");
string str;
getline(cin, str);
cout << "反转后字符串为" << endl;
string result=function.reverseString(str);
cout << result<< endl;
}
方法二
class Solution {
public:
/**
* @param s: a string
* @return: return a string
*/
string reverseString(string &s) {
// write your code here
int len = s.size();
int start = 0, end = len-1;
while(start < end) {
swap(s[start++], s[end--]);
}
for( int i = 0; i < s.size();++i )
{
if( s[i] == '\\' && i - 1 >= 0 )
{
swap(s[i], s[i - 1]);
}
}
return s;
}
void swap(char &a, char &b) {
char temp = a;
a = b;
b = temp;
}
};