题目描述:
将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
原理分析:
分析新组成的字符序列与numRows的关系,不难发现,当numRows=4时,第一行PIN,原序列P索引加上6便是I,而I的索引加上6便是N。同样寻找第二行的规律,A--L--S,则A的原序列索引加上6便是S。可以看出这个编程问题是一个周期问题。
拿第二行来研究索引与numRows的关系,A到L索引加4,L到S索引加2;S到I索引加4,I到G索引加2。也就是说索引的变化是交替的(+4+2).同样容易得出第三行的规律是交替的(+2+4)。因此我们可以分别用t1,t2来这是中间的间隔,并且间隔满足t1+t2=6.容易得到周期的大小T=(numRows-1)+(numRows-2)+1.
其次,在编写代码的时候,要注意边界条件的判断,以及t1,t2的更新。
编写语言:C++
代码实现:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string Z_arrange(string s, int nRows);
int main()
{
//string s = "PAYPALISHIRING";
//string s = "A";
string s = "AB";
int nRows;
string s1;
cout << "请输入行数:" << endl;
while (cin >> nRows)
{
s1 = Z_arrange(s, nRows);
}
return 0;
}
string Z_arrange(string s, int nRows)
{
if (s.size() <= nRows||nRows==1)
{
cout << "字符串的长度小于nRows,直接打印原字符串:" << s << endl;
return s;
}
int T = (nRows - 1) + (nRows - 2) + 1;
cout << "循环周期为:" << T << endl;
string s1;
//int t1=0,t2=T;
int t1 = T, t2 = 0;
int j = 0;
for (int i = 0; i < nRows; i++)
{
if (t1 == 0 || t2 == 0)
{
j = i;
while (j < s.size())
{
s1.push_back(s[j]);
j = j + T;
}
//t1 = t1 + 2;
//t2 = T - 2;
t1 = t1 - 2;
t2 = t2 + 2;
/*
if (t1 > T)
t1 = t1 - T;
if (t2 < 0)
t2 = t2 + T;
*/
if (t2 > T)
t2 = t2 - T;
if (t1 < 0)
t1 = t1 + T;
j = 0;
}
else
{
s1.push_back(s[i]);
j = i;
while (j < s.size())
{
if (j + t1 >= s.size())
break;
j = j + t1;
s1.push_back(s[j]);
if (j + t2 >= s.size())
break;
j = j + t2;
s1.push_back(s[j]);
}
//t1 = t1 + 2;
//t2 = t2 - 2;
t1 = t1 - 2;
t2 = t2 + 2;
/*
if (t1 > T)
t1 = t1 - T;
if (t2 < 0)
t2 = t2 + T;
*/
if (t2 > T)
t2 = t2 - T;
if (t1 < 0)
t1 = t1 + T;
}
}
cout << "Z排列之后的顺序是:" << s1 << endl;
return s1;
}