【问题描述】
一个长度为n(1=<n<=1000)的字符串s(原文,可能包括空格)可以通过以下算法进行加密
a). 按递减顺序迭代n的所有因子,也就是从n到1
b). 对于每个因子d,反转字符串s的前d个字符s[0,…,d-1],从而形成新的s
给定一个已加密的字符串t(密文),你的任务是找出原始字符串s(原文),输入保证字符串s是存在且唯一的。
【输入形式】
输入为一行一个字符串t,表示密在这里插入代码片文
【输出形式】
输出原文字符串s
【样例输入】
owrldolleh
【样例输出】
helloworld
【样例说明】
原文s “helloworld”
长度为10,其因子依次为10,5,2,1
第一次变换反序前10个字符:“dlrowolleh”
第二次变换反序前5个字符:“worldolleh”
第三次变换反序前2个字符:“owrldolleh”
第四次变换反序前1个字符:“owrldolleh”
密文为"owrldolleh"
注意,最后的反转操作不改变字符串,因为d=1。
旧题新想法,别人写好的函数不用可惜了ヽ(ー_ー)ノ
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdlib.h>
using namespace std;
int main()
{
string cipher; //密文原文
vector<int> divisor;//因子
getline(cin,cipher);
int len = cipher.size();
for (size_t i = 1; i <= len; i++)
{
if (len % i == 0)
{
divisor.push_back(i);
}
}
for (int div : divisor) //这种写法可以遍历容器vector内的元素
{
//调用algorithm头文件里的函数,需使用迭代器
reverse(cipher.begin(), cipher.begin() + div);
}
cout << cipher << endl;
system("pause");
return 0;
}