描述
写一个递归算法来实现字符串的逆序存储,要求空间复杂度为O(1)。
输入
多组数据,每组数据有一行,为要求逆序存储的字符串。当输入字符串为“0”时,输入结束。
输出
对于每组数据输出一行,为逆序存储后的字符串。
输入样例 1
ABCDE 12345 0
输出样例 1
EDCBA 54321
#include <iostream>
#include<string>
using namespace std;
string Upsidedown(const string &str)
{
if(str.length()<=1)
return str;
return Upsidedown(str.substr(1))+str[0];
}
int main()
{
string str;
while(1)
{
cin>>str;
if(str=="0")break;
cout<<Upsidedown(str)<<endl;
}
return 0;
}
原博地址
https://blog.csdn.net/weixin_43673589